问题
I want the user to enter a string and if the string does not match my regex expression then I want a message to be outputted and the user to enter a value again.
The problem is even when the string matches the regex it is treating it as if it does not match.
My regex:
This should equal - Name, Name
[[A-Z][a-zA-Z]*,\s[A-Z][a-zA-Z]*]
My while
loop:
System.out.println("Enter the student's name in the following format - surname, forename: "); studentName = input.next();
while (!studentName.equals("[[A-Z][a-zA-Z]*,\\s[A-Z][a-zA-Z]*]")) {
System.out.println("try again");
studentName = input.next();
}
回答1:
The equals
methods checks for string equivalence, not for matching regular expressions.
Just replace equals
with matches
. You should also remove the outer square brackets.
回答2:
Could it be that your regexp is wrong?
test.matches("[A-Z][a-zA-Z]*,\\s[A-Z][a-zA-Z]*")
works fine for me.
来源:https://stackoverflow.com/questions/20305074/java-comparing-string-to-regex-while-loop