A regular expression for a password that requires one numeric or one non-alphanumeric character

I am looking for a rather specific regular expression, and I have almost none, but not quite.

I want a regular expression that requires at least 5 characters, where at least one of these characters is either a numeric value or a non-character character.

This is what I still have:

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

So the problem is in the "or" part. This will allow non-alphanumeric values ​​to be used, but at least one numerical value is still required. You can see that I have a statement or a "|" between my required numbers and non-alphanumeric, but that doesn't seem to work.

Any suggestions would be great.

+7
regex
source share
5 answers

Try:

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

Brief 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 
+19
source share

Maybe this might work for you:

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

And use code like this to check the size of the string:

 if(str.len >= 5 && str.len =< 20 && regex.ismatch(str, "^.*[\d\W]+.*$")) { ... } 
+1
source share

How about this?

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

For length 5.20 Use the regular strlen function

0
source share

Is it really necessary to stuff everything in a giant regular expression? Just use program logic (5 ≀ length(s) ≀ 20) ∧ (/[[:digit:]]/ ∨ /[^[:alpha:]]/) . I think it is much more readable syntactically and semantically.

0
source share

A fairly simple solution, as soon as S. Mark made me on the right track, I just needed to combine my numerical and non-alphanumeric fragments as one.

Here's the last regex for anyone interested:

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

This will allow any password to be used between 5 and 20 characters and requires at least one letter and one numeric and / or one non-alphanumeric character.

0
source share

All Articles