Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need a specific regex pattern for Java and Javascript

I need a regular expression with following conditions:

  • min 5 characters, no max characters (only letters and numbers)
  • must contain minimum 4 letters
  • must contain minimum 1 number

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!

like image 991
Zwammer Avatar asked Apr 27 '26 02:04

Zwammer


1 Answers

.{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).

like image 194
Loamhoof Avatar answered Apr 28 '26 15:04

Loamhoof