正则表达式以匹配两个字符之一 [英] Regular expression to match one of two characters

查看:42
本文介绍了正则表达式以匹配两个字符之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用什么正则表达式来确保输入匹配字符'a'或字符'x'.

What regular expression can I use to make sure input matches either a character 'a' or character 'x'.

我尝试了以下方法,但是这并没有达到我的期望.

I have tried the following but this doesn't work as I had hoped.

char option;

Console.WriteLine("Please make your option");
for (int i = 0; i < options.Length; i++)
{
    Console.WriteLine(options[i]);

}
option = char.Parse(Console.ReadLine());
while (option != 'a' || option != 'x')
{
    Console.WriteLine("'a' or 'x' please!!");
    option = char.Parse(Console.ReadLine());
}

我想要的是仅接受两个字符之一作为输入.

What I want is for one of the two characters to be accepted only...as input.

推荐答案

不需要正则表达式,这里有逻辑错误,需要使用&& (AND)逻辑运算符代替在您的while循环中 || (OR):

No regex is needed, you have logic error here, you need to use && (AND) logic operator instead of || (OR) in your while loop:

while (option != 'a' && option != 'x')

这篇关于正则表达式以匹配两个字符之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆