Regex for checking that at least 3 of 4 different character groups exist

Just to learn – would this kind of requirement be possible to implement in pure regex?

That’d make it a rather hard to read (and therefor maintain!) solution, but here it is:

(?mx)
^
(
  (?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])                # must contain a-z, A-Z and 0-9
  |                                                # OR
  (?=.*[a-z])(?=.*[A-Z])(?=.*[!@\#$%&/=?_.,:;\\-]) # must contain a-z, A-Z and special
  |                                                # OR
  (?=.*[a-z])(?=.*[0-9])(?=.*[!@\#$%&/=?_.,:;\\-]) # must contain a-z, 0-9 and special
  |                                                # OR
  (?=.*[A-Z])(?=.*[0-9])(?=.*[!@\#$%&/=?_.,:;\\-]) # must contain A-Z, 0-9 and special
)
.{8,}                                              # at least 8 chars
$

A (horrible) Javascript demo:

var pw = "aa$aa1aa";
if(pw.match(/^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&\/=?_.,:;\\-])|(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%&\/=?_.,:;\\-])|(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%&\/=?_.,:;\\-])).{8,}$/)) {
  print('Okay!');
} else {
  print('Fail...');
}

prints: Okay!, as you can see on Ideone.

Leave a Comment