1

I wish to write a regex that will match strings with numbers.

I have the following regular expression which kind of works:

[a-z0-9]*([a-z]+[0-9]+)+[a-z0-9]*

results:

abc1234aa121aaa //Matches
abc123  //Matches
12abc123sd12 //Matches
abcaaaaaa //Does not match
ab12b12b12b2321b3  //Matches
ab12b12b12b2321b //Matches
1abc1234aa121aaa //Matches
v2  //Matches

but it doesn't work if I wanted to match strings with length 5 or greater

([a-z0-9]*([a-z]+[0-9]+)+[a-z0-9]*){5,}
Siddharth
  • 396
  • 2
  • 14
  • Edited the question with my attempt. – Siddharth Nov 03 '19 at 11:09
  • Possible duplicate of [Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"](https://stackoverflow.com/questions/9477906/regular-expression-to-check-if-password-is-8-characters-including-1-uppercase-l) – Matt Timmermans Nov 03 '19 at 13:40

2 Answers2

1
(?=\w{5,})\w*[0-9]+\w*

This should help you. This regex matches any string of word characters (That's the \w*[0-9]+\w*, where \w is shorthand for [a-zA-Z0-9_])

At the beginning, there is a positive lookahead which asserts that there are at least 5 word characters in a row in the match. This way, any less than 5 characters in the word will fail the lookahead.

anerisgreat
  • 342
  • 1
  • 7
  • 1
    @Siddharth: Be aware this is matching strings without letters like: `123456789` or `__123__` – Toto Nov 03 '19 at 15:25
0

In the first pattern v2 matches but as you have a fixed order [a-z]+[0-9]+ then 2v would for example not match.

As you use a quantifier {5,} in the second pattern and use [a-z]+[0-9]+ the minimum length would be at least 10.

If you want to match a string with alphabets AND numbers with length greater than n so only digits should not match, you could use:

\b(?=[a-z0-9]{5,})(?=[a-z0-9]*[a-z])[a-z0-9]*[0-9][a-z0-9]*\b
  • \b Word boundary
  • (?=[a-z0-9]{5,}) Assert 5 or more times a char a-z or a digit 0-9
  • (?=[a-z0-9]*[a-z]) Assert at least 1 char a-z
  • [a-z0-9]* Match 0+ times a-z or 0-9
  • [0-9] Match a digit 0-9
  • [a-z0-9]* Match 0+ times a-z or 0-9
  • \b Word boundary

Regex demo

In Java

String regex = "\\b(?=[a-z0-9]{5,})(?=[a-z0-9]*[a-z])[a-z0-9]*[0-9][a-z0-9]*\\b";
The fourth bird
  • 154,723
  • 16
  • 55
  • 70