3

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!

5
  • min 5 chars, but is it restricted to numbers and letters? Commented Apr 23, 2013 at 12:48
  • Yes, I should specify that. Question edited. Commented Apr 23, 2013 at 12:50
  • I'm not even sure the criteria can be checked with regex, it's too dynamic. Commented Apr 23, 2013 at 12:55
  • ro1ot seems not matches ^(?=.*\d{1,})(?=.*[a-zA-Z]{4,}).{5,}$ Commented Apr 23, 2013 at 12:57
  • Accepted Loamhoof's answer. Commented Apr 23, 2013 at 13:17

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Zwammer seen another problem also (and making some improvement). Editing
Thanks! This works like a charm. Regex can be quite a mystery for the inexperienced :D
1

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]*$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.