3

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();
  }
Colin747
  • 4,955
  • 18
  • 70
  • 118

2 Answers2

5

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.

phlogratos
  • 13,234
  • 1
  • 32
  • 37
  • When I do that it matches the wrong way round. i.e. if it's in the format I want it reports an error. If I remove the `!` in front `!studentName.equals` it reports an error when it does match the regex – Colin747 Nov 30 '13 at 20:14
  • I have `while (!studentName.matches("[A-Z][a-zA-Z]*,\\s[A-Z][a-zA-Z]*"))` but when I try `Name, Name` it prints `Try Again` twice – Colin747 Nov 30 '13 at 20:20
  • Probably `Name, Name` are to separate strings in your input. Try adding the wrong input in the message you print. – phlogratos Nov 30 '13 at 20:24
  • Looks like you're right, it's printing `Name, try again Name try again` How can I fix this? – Colin747 Nov 30 '13 at 20:26
  • We can only help you if you provide us some more infos about your input, – phlogratos Nov 30 '13 at 20:28
  • What is `input` ? Which class ? Where do the values come from ? – phlogratos Nov 30 '13 at 20:32
  • `Input` is using `scanner`, The user is prompted to enter a name which is then entered into a array. `Scanner input = new Scanner(System.in);` – Colin747 Nov 30 '13 at 20:34
  • Scanner is splitting if a whitespace appears in the user input. Just print out the user input after you assigned it to studentName the first time and you will see it for yourself. – Ben Nov 30 '13 at 20:36
  • 1
    The `Scanner` javadoc says: `A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace` – phlogratos Nov 30 '13 at 20:36
  • Like phlogratos mentioned, change the delimiter using input.useDelimiter(); and it will work – Ben Nov 30 '13 at 20:39
3

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.

Ben
  • 1,157
  • 6
  • 11