Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java comparing string to regex - while loop

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();
  }
like image 221
Colin747 Avatar asked Jan 17 '26 19:01

Colin747


2 Answers

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.

like image 160
phlogratos Avatar answered Jan 20 '26 09:01

phlogratos


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.

like image 21
Ben Avatar answered Jan 20 '26 11:01

Ben