I wrote a program that asks the use to input a string of 3 characters, which could be a combination of [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.
I entered a test string of: a^b, but the loop just keeps going.
How do I fix this?
Thanks.
The correct regular expression is [AB^V]+
. Indeed the original expression would only match strings of length 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.