2013-06-04 46 views
0

为什么这会返回false我输入的任何正常单词?正则表达式返回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."); 
    } 

我必须缺少一些东西。

回答

1

你的正则表达式只匹配一个字符长的字符串。
要匹配字符的一个或多个号码将其更改为:

"[a-zA-Z0-9\\s]+" 

您可能还会发现这个(IMO大)Regular-Expressions reference有用。

1

你需要的是[a-zA-Z0-9\\s]+。最后加上+

0

因为您应该在正则表达式的末尾添加'+',否则您只需要匹配一个字符。

0

在正则表达式中,您可以在范围末尾使用+来指定“多于一个”,而在您的情况下,您只能探测长度为1的表达式。

0

试试这个正则表达式 “^ [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."); 
}