Regex (regular expression) for password validation

2019-01-20 05:39发布

问题:

What would be the correct regex, to satisfy the following password criteria:

  • Must include at least 1 lower-case letter.
  • Must include at least 1 upper-case letter.
  • Must include at least 1 number.
  • Must include at least 1 special character (only the following special characters are allowed: !#%).
  • Must NOT include any other characters then A-Za-z0-9!#% (must not include ; for example).
  • Must be from 8 to 32 characters long.

This is what i tried, but it doesn't work:

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[\!\#\@\$\%\&\/\(\)\=\?\*\-\+\-\_\.\:\;\,\]\[\{\}\^]).{8,32}

But it should be:

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[\!\#\@\$\%\&\/\(\)\=\?\*\-\+\-\_\.\:\;\,\]\[\{\}\^])[A-Za-z0-9!#%]{8,32}

But Unihedron's solution is better anyways, just wanted to mention this for the users which will read this question in the future. :)

Unihedron's solution (can also be found in his answer below, i copied it for myself, just in case he changes (updates it to an better version) it in his answer):

^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[!#%])[A-Za-z0-9!#%]{8,32}$

I ended up with the following regex:

^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*?[\!\#\@\$\%\&\/\(\)\=\?\*\-\+\-\_\.\:\;\,\]\[\{\}\^])[A-Za-z0-9\!\#\@\$\%\&\/\(\)\=\?\*\-\+\-\_\.\:\;\,\]\[\{\}\^]{8,60}$

Thanks again Unihedron and skamazin. Appreciated!

回答1:

Use this regex:

/^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=[^!#%]*[!#%])[A-Za-z0-9!#%]{8,32}$/

Here is a regex demo!


Read more:

  • Regex for existence of some words whose order doesn't matter


回答2:

Test your possible passwords on this and see if they give you the proper result

The regex I used is:

^(?=.*[a-z])(?=.*[A-Z])(?=.*?[0-9])(?=.*?[!#%])[A-Za-z0-9!#%]{8,32}$