[英]Detecting 11 adjacent digits with RegEx
How I can detect 11 adjacent (ie 11 digits no other characters in between) digits with RegEx? 如何使用RegEx检测11个相邻的(即11个数字,中间没有其他字符)数字?
ie it should match asd 12345678901 asd 11
and AA12345678901as
即它应该匹配
asd 12345678901 asd 11
和AA12345678901as
but NOT asd 123456789012 asd 11
because it has 12 adjacent digits 但不是
asd 123456789012 asd 11
因为它有12个相邻数字
I tried (^[0-9])*(\\d{11})(^[0-9])*
but it matches asd 123456789012 asd 11
我尝试过
(^[0-9])*(\\d{11})(^[0-9])*
但它匹配asd 123456789012 asd 11
尝试\\b\\d{11}\\b
,它指定11位数字周围的单词边界,因此您不匹配12个长度的前11个字符。
You can do this with look-around: 您可以通过环顾四周来做到这一点:
(?<!\d)\d{11}(?!\d)
It will match a sequence of exactly 11 digits, and you can be sure that in front or behind it doesn't have any other digit (it can be any other characters, though, such as alphabet, space, etc.). 它会与正好是11个数字的序列匹配,并且可以确保在它的前面或后面没有其他数字(但是可以是任何其他字符,例如字母,空格等)。
So these strings are considered to contain a match: jhgjad12345678901
, 12345678901
, 12345678901skjdhks
, sdfjhsdf 12345678901 sdfjgj 2342 sdkfl
, =-=342_12345678901:}{]'
因此,这些字符串被认为包含匹配:
jhgjad12345678901
, 12345678901
, 12345678901skjdhks
, sdfjhsdf 12345678901 sdfjgj 2342 sdkfl
, =-=342_12345678901:}{]'
Or another way, without look-around: 或另一种方式,无需环顾四周:
(?:\D|^)(\d{11})(?:\D|$)
The 11-digit number will be in the capturing group 1. 11位数字将在捕获组1中。
You can use IsMatch
method with the above regex to check whether the string has a sequence of exactly 11 digits. 您可以在上面的正则表达式中使用
IsMatch
方法,以检查字符串是否完全由11位数字组成。 You can use Match
or Matches
method to find one or all (respectively) the sequence in the string. 您可以使用
Match
或Matches
方法在字符串中查找一个或所有(分别)序列。
That would be 那会是
[^\d]+\d{11}[^\d]+
You are almost there. 你快到了 Just you need to make sure that there is exactly one
non-digit
before and after your sequence. 只需确保序列前后有一个
non-digit
。 So, you need to insert a [^\\d]
without any quantifier at both ends. 因此,您需要在两端插入没有任何量词的
[^\\d]
。
You can try this regex: - 您可以尝试以下正则表达式:-
(?:.*?[^\d]|^)\d{11}(?:[^\d].*|$)
See demo: - http://www.myregextester.com/?r=14ad3bb5 观看演示:-http://www.myregextester.com/?r= 14ad3bb5
The above regex matches following strings: - 上面的正则表达式匹配以下字符串:-
asd 12345678901 asd 11
12341234234
af23412434353 saf // 11 digits preceded by characters. I suppose you expect it to match.
and rejects this string: - 并拒绝此字符串:-
asd 123456789012 asd 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.