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();
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With