简体   繁体   English

一个正则表达式来匹配长度大于 n 的字母和数字的字符串?

[英]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但如果我想匹配长度为 5 或更大的字符串,它就不起作用

([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_])此正则表达式匹配任何单词字符串(即 \w*[0-9]+\w*,其中 \w 是 [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.一开始,有一个肯定的前瞻,它断言匹配中的一行中至少有 5 个单词字符。 This way, any less than 5 characters in the word will fail the lookahead.这样,单词中任何少于 5 个字符的字符都将失败。

In the first pattern v2 matches but as you have a fixed order [az]+[0-9]+ then 2v would for example not match.在第一个模式中, v2匹配,但由于您有固定的顺序[az]+[0-9]+ ,因此2v例如不匹配。

As you use a quantifier {5,} in the second pattern and use [az]+[0-9]+ the minimum length would be at least 10.当您在第二个模式中使用量词{5,}并使用[az]+[0-9]+时,最小长度至少为 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:如果你想match a string with alphabets AND numbers with length greater than n那么只有数字不应该匹配,你可以使用:

\b(?=[a-z0-9]{5,})(?=[a-z0-9]*[a-z])[a-z0-9]*[0-9][a-z0-9]*\b
  • \b Word boundary \b字边界
  • (?=[a-z0-9]{5,}) Assert 5 or more times a char az or a digit 0-9 (?=[a-z0-9]{5,})断言 5 次或更多次 char az 或数字 0-9
  • (?=[a-z0-9]*[az]) Assert at least 1 char az (?=[a-z0-9]*[az])断言至少 1 个字符 az
  • [a-z0-9]* Match 0+ times az or 0-9 [a-z0-9]*匹配 0+ 次 az 或 0-9
  • [0-9] Match a digit 0-9 [0-9]匹配一个数字 0-9
  • [a-z0-9]* Match 0+ times az or 0-9 [a-z0-9]*匹配 0+ 次 az 或 0-9
  • \b Word boundary \b字边界

Regex demo正则表达式演示

In Java在 Java

String regex = "\\b(?=[a-z0-9]{5,})(?=[a-z0-9]*[a-z])[a-z0-9]*[0-9][a-z0-9]*\\b";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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