Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match x out of y groups in Java regex

Tags:

java

regex

Is it possible to write a regex pattern in Java that will match, for example, 2 out of 3 (or 3 out of 4 etc) groups?

For example, I have the following regex:

((?=.*\d)(?=.*[a-z])(?=.*[A-Z]))

which will only allow patterns that match all three groups - i.e. it must contain a number AND a lowercase character AND an uppercase character. I'd like to make it so that it will validate a pattern that contains at least two out of the three groups (e.g. a number and an Uppercase character OR a lower and uppercase characters).

Is it doable in a single statement or am I going to have to write separate regexes and loop through them?

like image 800
TrailDragon Avatar asked Jul 23 '15 12:07

TrailDragon


1 Answers

You will need alternations to account for all the possible scenarios:

((?=.*\d)(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])|(?=.*[a-z])(?=.*[A-Z]))

See demo that also matches the whole string with matches():

((?=.*\d)(?=.*[a-z])|^(?=.*\d)(?=.*[A-Z])|^(?=.*[a-z])(?=.*[A-Z])).*
like image 100
Wiktor Stribiżew Avatar answered Nov 15 '22 01:11

Wiktor Stribiżew