Java将字符串与正则表达式进行比较-While循环 [英] 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.
我的正则表达式:
这应该等于-Name, Name
My regex:
This should equal - Name, Name
[[A-Z][a-zA-Z]*,\s[A-Z][a-zA-Z]*]
我的while
循环:
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();
}
推荐答案
equals
方法检查字符串是否等效,而不是匹配正则表达式.
The equals
methods checks for string equivalence, not for matching regular expressions.
只需将equals
替换为matches
.您还应该卸下外部方括号.
Just replace equals
with matches
. You should also remove the outer square brackets.
这篇关于Java将字符串与正则表达式进行比较-While循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!