Java comparing string to regex - while loop

人盡茶涼 提交于 2020-07-16 02:48:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!