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?
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])).*
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