How come the following returns true?
Pattern.compile("(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,12})").matcher("passworD12345678").find();
Shouldn't it fail on (?=.{8,12}) since its length is outside of the range?
find() doesn't check if entire string can be matched by regex, matches() does. find simply tries to find any substring which can be matched by regex. Also (?=.{8,12}) check if there is place which has 8 to 12 characters after it. So either add anchors ^ $ in your regex representing start and end of the string like
Pattern.compile("^(?=.*[A-Z])"
+ "(?=.*[a-z])"
+ "(?=.*[0-9])"
+ "(?=.{8,12}$)").matcher("passworD12345678").find();
or use matches() with this regex
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With