Java正则表达式意外匹配

时间:2015-02-24 22:01:11

标签: java regex

以下是如何返回true的?

Pattern.compile("(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,12})").matcher("passworD12345678").find();

(?=.{8,12})不应该失败,因为它的长度超出了范围吗?

1 个答案:

答案 0 :(得分:11)

find()不检查正则表达式是否匹配整个字符串,matches()是否匹配。 find只是试图找到可以由正则表达式匹配的任何子字符串。另外(?=.{8,12})检查后面是否有8到12个字符的地方。因此,请在正则表达式中添加anchors ^ $,表示字符串的开头和结尾,如

Pattern.compile("^(?=.*[A-Z])"
                + "(?=.*[a-z])"
                + "(?=.*[0-9])"
                + "(?=.{8,12}$)").matcher("passworD12345678").find();

或使用matches()使用此正则表达式

Pattern.compile("(?=.*[A-Z])"
                + "(?=.*[a-z])"
                + "(?=.*[0-9])"
                + ".{8,12}").matcher("passworD12345678").matches();
//                 ^^^^^^^ we can't use look-ahead because we need some part of regex 
//                         which will let regex consume all characters from string