Reputation: 13
I am using RegEx in Java to classify phone numbers and I am stuck finding consecutive repeating numbers.
Why is this RegEx
9{4}([0-8]\1{2})([0-9]\1{3})[0-9]
Not matching this string
9999227771
Upvotes: 1
Views: 80
Reputation: 87203
In the regex
9{4}([0-8]\1{2})([0-9]\1{3})[0-9]
([0-8]\1{2})
This is first capturing group and inside that \1
- back-reference refers to itself which will not work.
In the second captured group ([0-9]\1{3})
, you are again referring to first captured group.
Also, both the back-references are repeated n
times which should be n-1
as first number is matched by the capturing group.
Here is corrected regex
9{4}([0-8])\1([0-9])\2{2}[0-9]
9{4}
: Repeat 9
four times. i.e. 9999([0-8])\1
: Match a number in the given range and match the same number again, thus \1
.([0-9])\2{2}
: Match a digit and follow it by same digit twiceNote: To match exact phone numbers, use anchors ^
and $
.
Upvotes: 2