[英]Check String for values other than those allowed. Java
I wrote a program that asks the use to input a string of 3 characters, which could be a combination of [a, b, v, ^]; 我编写了一个程序,要求使用该程序输入3个字符的字符串,该字符串可以是[a,b,v,^]的组合。
Here's what I have so far: 这是我到目前为止的内容:
do {
System.out.print("Enter a two variable logical expression, no spaces: "); // 'v' for or, '^' for and.
expression = type.nextLine();
}
while ((expression.length() != 3) || !((expression.toUpperCase()).matches("[AB^V]")));
The loop is only suppose to continue when the string is not 3 characters long, or a character in the string is not allowed. 仅当字符串长度不超过3个字符或不允许字符串中的字符时才继续循环。
I entered a test string of: a^b, but the loop just keeps going. 我输入了一个测试字符串:a ^ b,但是循环一直在继续。
How do I fix this? 我该如何解决?
Thanks. 谢谢。
The correct regular expression is [AB^V]+
. 正确的正则表达式为
[AB^V]+
。 Indeed the original expression would only match strings of length 1. 实际上,原始表达式只能匹配长度为1的字符串。
((expression.toUpperCase()).matches("[AB^V]+"))
^
does not need to be escaped, since it is between [
and ]
(ie in a character class). ^
不需要转义,因为它在[
和]
之间(即在字符类中)。
Edit : actually ^
should be escaped if it was at the beginning of the character class (like in [\\\\^ABV]+
), but not when it is preceded by other characters. 编辑 :实际上,如果
^
在字符类的开头(例如[\\\\^ABV]+
),则应该转义,但在其他字符之后则不应转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.