Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression matches unexpectedly

Tags:

java

regex

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?

like image 638
Glide Avatar asked Feb 27 '26 04:02

Glide


1 Answers

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
like image 169
Pshemo Avatar answered Feb 28 '26 17:02

Pshemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!