转载请注明出处:http://blog.csdn.net/moushao/article/details/54410443
最近的项目需要用到一个很复杂的校验条件,一个正则表达式构建不出来,于是我分成4个单独构建
比如如此:
private static boolean isContainSpecialChar(String passWord)
{
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(passWord);
return m.find();
}
将传入的字符串校验,看是否为特殊字符。
注意最后的m.find()方法,它其实就是匹配的结果,匹配成功为true,失败为false,
但问题是,一个匹配器中, m.find()只能用一次。
比如
boolean b = m.find();
private static boolean isContainSpecialChar(String passWord)
{
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(passWord);
boolean b = m.find();
return m.find();//第二次用m.find()
}
这个时候,即使是b = true,但return的结果,会是false。
查了一下Matcher.find 的API说明:
Returns the next occurrence of the Pattern
in the input. If a previous match was successful, the method continues the search from the first character following that match in the input. Otherwise it searches either from the region start (if one has been set), or from position 0.
也就是说如果前一个匹配成功,则该方法将继续从输入中的匹配后面的第一个字符搜索.。否则,它会搜索从区域开始(如果已设置),或从位置0。
当我第二次开始调用m.find的时候,因为第一次匹配成功了,他会从第一次传入字符password后面继续匹配,但是password后,没值,为空,所以自然为false了!!!
这个真的是坑死爹爹了!