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

后端 未结 6 659
一个人的身影
一个人的身影 2020-12-01 13:04

I\'m trying to write a password validator.

How can I see if my supplied string contains at least 3 different character groups?

It\'s easy enough to check if

6条回答
  •  离开以前
    2020-12-01 13:33

    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.

提交回复
热议问题