Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for password that requires one numeric or one non-alphanumeric character

Tags:

regex

I'm looking for a rather specific regex and I almost have it but not quite.

I want a regex that will require at least 5 charactors, where at least one of those characters is either a numeric value or a nonalphanumeric character.

This is what I have so far:

^(?=.*[\d]|[!@#$%\^*()_\-+=\[{\]};:|\./])(?=.*[a-z]).{5,20}$

So the problem is the "or" part. It will allow non-alphanumeric values, but still requires at least one numeric value. You can see that I have the or operator "|" between my require numerics and the non-alphanumeric, but that doesn't seem to work.

Any suggestions would be great.

like image 887
Chris Nicol Avatar asked Jan 04 '10 05:01

Chris Nicol


2 Answers

Try:

^(?=.*(\d|\W)).{5,20}$

A short explanation:

^                         # match the beginning of the input
(?=                       # start positive look ahead
  .*                      #   match any character except line breaks and repeat it zero or more times
  (                       #   start capture group 1
    \d                    #     match a digit: [0-9]
    |                     #     OR
    \W                    #     match a non-word character: [^\w]
  )                       #   end capture group 1
)                         # end positive look ahead
.{5,20}                   # match any character except line breaks and repeat it between 5 and 20 times
$                         # match the end of the input
like image 111
Bart Kiers Avatar answered Nov 13 '22 03:11

Bart Kiers


Perhaps this may work for you:

^.*[\d\W]+.*$

And use some code like this to check string size:

if(str.len >= 5 && str.len =< 20 && regex.ismatch(str, "^.*[\d\W]+.*$")) { ... }
like image 33
Bob Avatar answered Nov 13 '22 04:11

Bob