Java 验证regex返回值为false
为什么我输入的任何正常单词都返回falseJava 验证regex返回值为false,java,regex,Java,Regex,为什么我输入的任何正常单词都返回false if(!guestbook.getName().matches("[a-zA-Z0-9\\s]")) { errors.rejectValue("name", "stringFormat.falseCharacters", "You are only allowed to use numbers, letters and spaces for the name."); } 我一定遗漏了什么。您的正则表达式只匹配一个字符长的字符
if(!guestbook.getName().matches("[a-zA-Z0-9\\s]")) {
errors.rejectValue("name", "stringFormat.falseCharacters", "You are only allowed to use numbers, letters and spaces for the name.");
}
我一定遗漏了什么。您的正则表达式只匹配一个字符长的字符串。
要匹配一个或多个字符数,请将其更改为:
"[a-zA-Z0-9\\s]+"
你可能也会发现这个(我很好)很有用。你需要的是
[a-zA-Z0-9\\s]+
。在末尾添加+
。因为您应该在正则表达式的末尾添加“+”,否则您只请求一个字符的匹配。在正则表达式中,您使用范围末尾的+
指定“多个”而在您的例子中,您只探测长度为1的表达式。请尝试此正则表达式“^[a-Za-z0-9\s]+$”
if(!guestbook.getName().matches("^[A-Za-z0-9\\s]+$")) {
errors.rejectValue("name", "stringFormat.falseCharacters", "You are only allowed to use numbers, letters and spaces for the name.");
}