I need to match a group of exact 5 characters 1's. Example below
02011111020 // match
00211111200 // Not match because there are 2 at start and end of group
00111111100 // Not match because there are 6 1's
So far, I have try with pattern
(?!2)(1{5}?)(?!2)
but fail at00111111100
\D(1{5}?)\D
but fail at02011111020
CodePudding user response:
This condition (?!2)
is always true as the next character to match is a 1 and this condition (?!2)
asserts not a 2, which will be true if there is still a 1 to the right.
This \D
means matching a character other than a digit, which can never match in a string with only digits.
You can exclude matching 1 and 2 using a character class [12]
and lookarounds:
(?<![12])1{5}(?![12])
The pattern matches:
(?<![12])
Negative lookbehind, assert not 1 or 2 to the left1{5}
match 5 times a 1(?![12])
Negative lookahead, assert not 1 or 2 to the right
CodePudding user response:
Matching a line with 5 consecutive 1
s that are preceded and followed by a 0
:
.*01{5}0.*