T.S.
T.S.

Reputation: 19350

Regular expression pattern fails

I have this pattern

"^((?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[#@$])).{4,10}$"

And it seem doing its job checking existence of letter, digit and a special character

Now, I want to add a twist - I want first character to be a letter or digit. And this is not working

"^([a-zA-Z0-9](?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[#@$])).{4,10}$"

what is not working is - I can type 11 characters instead of 10.

I admit, so far I only checked it on this website, not in code. What do I need to do?

Upvotes: 0

Views: 31

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174716

Just change your regex to,

^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[#@$])[A-Za-z0-9].{3,9}$
                                            |--------| |
                                            | 1+3=4    |
                                            -----------|    
                                              1+9=10

This would allow atleast four characters and atmost 10 characters.

Your pattern matches 11 characters because [a-zA-Z0-9] at first takes a character. So you need to specify the range(after the first character) from 3 to 9 so that it would match atleast 4 and atmost 10.

DEMO

Upvotes: 3

Related Questions