How I can detect 11 adjacent (ie 11 digits no other characters in between) digits with RegEx?
ie it should match asd 12345678901 asd 11
and AA12345678901as
but NOT asd 123456789012 asd 11
because it has 12 adjacent digits
I tried (^[0-9])*(\\d{11})(^[0-9])*
but it matches 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.).
So these strings are considered to contain a match: 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.
You can use IsMatch
method with the above regex to check whether the string has a sequence of exactly 11 digits. You can use Match
or Matches
method to find one or all (respectively) the sequence in the string.
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. So, you need to insert a [^\\d]
without any quantifier at both ends.
You can try this regex: -
(?:.*?[^\d]|^)\d{11}(?:[^\d].*|$)
See demo: - 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
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.