Home > OS >  Regex for Alternating Numbers
Regex for Alternating Numbers

Time:09-26

I am trying to write a regex pattern for phone numbers consisting of 9 fixed digits.

I want to identify numbers that have two numbers alternating for four times such as 5XYXYXYXY

I used the below sample

number = 561616161

I tried the below pattern but it is not accurate

^5(\d)(?=\d\1). 

can someone point out what i am doing wrong?

CodePudding user response:

If you want to repeat 4 times 2 of the same pairs and matching 9 digits in total:

^(?=\d{9}$)\d*(\d\d)\1{3}\d*$

Explanation

  • ^ Start of string
  • (?=\d{9}$) Positive lookahead, assert 9 digits till the end of the string
  • \d* Match optional digits
  • (\d\d)\1{3} Capture group 1, match 2 digits and then repeat what is captured in group 1 3 times
  • \d* Match optional digits
  • $ End of string

Regex demo

If you want to match a pattern repeating 4 times 2 digits where the 2 digits are not the same:

^(?=\d{9}$)\d*((\d)(?!\2)\d)\1{3}\d*$

Explanation

  • ^ Start of string
  • (?=\d{9}$) Positive lookahead, assert 9 digits till the end of the string
  • \d* Match optional digits
  • ( Capture group 1
    • (\d) Capture group 2, match a single digit
    • (?!\2)\d Negative lookahead, assert not the same char as captured in group 2. If that is the case, then match a single digit
  • ) Close group 1
  • \1{3} Repeat the captured value of capture group 1 3 times
  • \d* Match optional digits
  • $ End of string

Regex demo

CodePudding user response:

I would use:

^(?=\d{9}$)\d*(\d)(\d)(?:\1\2){3}\d*$

Demo

Here is an explanation of the pattern:

  • ^ from the start of the number
  • (?=\d{9}$) assert exactly 9 digits
  • \d* match optional leading digits
  • (\d) capture a digit in \1
  • (\d) capture another digit in \2
  • (?:\1\2){3} match the XY combination 3 more times
  • \d* more optional digits
  • $ end of the number

CodePudding user response:

  1. My first guess from OP's self tried regex ^5(\d)(?=\d\1). without any own additions was a regex is needed to verify numbers starting with 5 and followed by 4 pairs of same two digits.

    ^5(\d\d)\1{3}$
    

    Demo at regex101

  2. The same idea with the "added guess" to disallow all same digits like e.g. 511111111

    ^5((\d)(?!\2)\d)\1{3}$
    

    Demo at regex101

  3. Guessing further that 5 is a variable value and assuming if one variable at start/end with the idea of taking out invalid values early - already having seen the other nice provided answers.

    ^(?=\d?(\d\d)\1{3})\d{9}$
    

    Demo at regex101

  4. Solution 3 with solution 2's assumption of two different digits in first pairing.

    ^(?=\d?((\d)(?!\2)\d)\1{3})\d{9}$
    

    Demo at regex101

Solutions 3 and 4 are most obvious playings with @4thBird's nice answer in changed order.

  • Related