Regular expression for Password Requirements for P

2019-09-07 10:59发布

问题:

Here are password requirements for PCI compliance:

  • Must contain at least one upper case letter
  • Must contain at least one lower case letter
  • Must contain at least one number
  • Must contain at least one special character such as #, !, ?, ^, or @.

Please tell me how to create such regulat expressions? I can`t figure out how to do it

回答1:

Don't do it as a single regex. There's no need to do it in a single regex, and it will be easier to change the rules, and be much easier to read, if you just make multiple regex checks.

If you were doing this in Perl, for example, you'd just do

my $ok =
    ($pw =~ /[a-z]/) &&  # Has at least one lowercase char
    ($pw =~ /[A-Z]/) &&  # Has at least one uppercase char
    ($pw =~ /\d/)    &&  # Has at least one digit
    ($pw =~ /[#!?^@]);   # Has punctuation

That is far easier to read later on when you have to maintain the code in the future.



回答2:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#\!\?\^@])$

the special characters are individually specified



回答3:

^.*\d.*[a-z].*[A-Z].*[#\!\?\^@].*$

Simply this should do it for you.