Reputation: 33
I need a regular expression with following conditions:
E.g. of correct results: root1 1root ro1ot Roo11t etc...
Currently I have the pattern ^(?=.*\d{1,})(?=.*[a-zA-Z]{4,}).{5,}$
But this seems to also accept special characters...?
Thanks a lot!
Upvotes: 3
Views: 118
Reputation: 9599
I know this is ugly, but this appears to work:
^[a-zA-Z0-9]*(([a-zA-Z]{4,}\d)|([a-zA-Z]{3,}\d[a-zA-Z]+)|([a-zA-Z]{2,}\d[a-zA-Z]{2,})|([a-zA-Z]+\d[a-zA-Z]{3,})|(\d[a-zA-Z]{4,}))[a-zA-Z0-9]*$
Upvotes: 1
Reputation: 8293
.{5,}
that's why it allows special characters (dot = everything (except line feeds and such in fact)). Change it to [a-z0-9]{5,}
or whatever you want.
Note: (?=.*\d{1,})(?=.*[a-zA-Z]{4,})
only check the 2th and 3rd requirement, but don't say anything about the wanted nature of the characters.
Edit:
Other problem: your specification says "at least 4 letters" but your regex says "4 consecutive letters". Also, use lazy quantifiers.
/^(?=.*?\d)(?=(?:.*?[a-z]){4})[a-z0-9]{5,}$/i
(?=.*?\d)
=> you don't need to check for more than 1 number, once you found it, stop.
(?=(?:.*?[a-z]){4})
=> changed to find 4 letters, but not consecutive. Also, added an insensitive case modifier i
at the end (in JS, in Java you're not declaring it the same way).
Upvotes: 6