Jarod Peachey
Jarod Peachey

Reputation: 22

Regex to check if string has at least 2 numbers and 1 capital letter

I need to create a regular expression to check if a password has at least 1 uppercase letter, at least 2 numbers, and ends with a $ (dollar sign).

I've been trying to figure it out, but I can only get as far as checking if there's at least 1 uppercase and one number, rather than two.

These should be valid:

4hg5Fjkjk$

fh@#Y5fFF5$

hgH5Hu6$


These should not be valid:

45tyghisu$ (No capital)

5THygfhy$ (Only one number)

Gh%hF45$h (No dollar sign at the end)


Here's what I have so far (checks for at least one number, one capital and dollar sign at the end)

/(?=.*[A-Z])(?=.*\d).*\$/ Any help would be greatly appreciated!

ps. I've looked on SO, and can't find anything relating to more than one required character.

Upvotes: 1

Views: 297

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

In your pattern you have to repeat asserting a digit twice instead of one time using for example (?=(?:[^\d\r\n]*\d){2}) using contrast.

If you don't want to allow spaces in the password, you could use \S+ to match 1+ times a non whitespace char.

You could use:

^(?=[^A-Z\r\n]*[A-Z])(?=(?:[^\d\r\n]*\d){2})\S+\$$

Regex demo

According to the given answer by the OP, the number of characters should be 9-15:

^(?=[^A-Z\r\n]*[A-Z])(?=(?:[^\d\r\n]*\d){2})\S{9,15}\$$

Regex demo

Upvotes: 1

Jarod Peachey
Jarod Peachey

Reputation: 22

thanks for all the answers. Looked through them, and I figured out a pretty simple way to do it using the regular expression below. I edited it to allow for setting a length on the password, just change the 9 and 15 to your desired lengths.

/^(?=.*[A-Z])(?=.*\d.*\d)[^\s]{9,15}\$$/

Upvotes: 0

Booboo
Booboo

Reputation: 44043

This RegEx is simple and makes no other assumptions about what characters may be in a password other than what was specified by the OP.

^(?=.*?[A-Z])(?=.*?\d.*?\d).*\$$

See Demo (Click ON "RUN TESTS")

Upvotes: 0

Related Questions