正则表达式Matcher给我挖的坑

转载请注明出处: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了!!!


这个真的是坑死爹爹了!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值