简体   繁体   中英

A regular expression to match a string with alphabets AND numbers with length greater than n?

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,}
(?=\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.

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

As you use a quantifier {5,} in the second pattern and use [az]+[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 az or a digit 0-9
  • (?=[a-z0-9]*[az]) Assert at least 1 char az
  • [a-z0-9]* Match 0+ times az or 0-9
  • [0-9] Match a digit 0-9
  • [a-z0-9]* Match 0+ times az 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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM