【发布时间】:2013-08-06 03:33:34
【问题描述】:
我想编写一个简单的正则表达式来检查给定字符串中是否存在任何特殊字符。我的正则表达式有效,但我不知道为什么它还包含所有数字,所以当我输入一些数字时它会返回错误。
我的代码:
//pattern to find if there is any special character in string
Pattern regex = Pattern.compile("[$&+,:;=?@#|'<>.-^*()%!]");
//matcher to find if there is any special character in string
Matcher matcher = regex.matcher(searchQuery.getSearchFor());
if(matcher.find())
{
errors.rejectValue("searchFor", "wrong_pattern.SearchQuery.searchForSpecialCharacters","Special characters are not allowed!");
}
【问题讨论】:
-
[]中的破折号应该被转义,它在那里有特殊含义。 -
¿¡ 所以你认为唯一存在的特殊字符是键盘上的那些!? :-)
-
没错。最好定义所有“非特殊”字符并将其设为否定。
-
是的,也许断言只使用您想要允许的字符会更明智。
-
能否提供解决方案 String.replace("\"", """)