Regular expression delimiting a numeric string

I am trying to figure out how to use a regex to pass a 6 digit numeric string. My problem is that the string can be any of six digits as long as it doesn't start with 12. So the first digit can be 1, but not if the second digit is 2. The second digit can be 2, but not if the first is 1 ...

I tried this, ([^1])([^2])(\d{4})

but it doesn't count both digits, so it blocks anything with 2 in the second place.

Thanks for any help.

+3


source to share


1 answer


you can use

^([02-9][0-9]|[0-9][013-9])[0-9]{4}$

      

See regex demo

More details

  • ^

    - beginning of line
  • ([02-9][0-9]|[0-9][013-9])

    - any of the two alternatives:
    • [02-9][0-9]

      - any number, but 1, and then any number
    • |

      - or
    • [0-9][013-9]

      - any number, then any number, but 2

  • [0-9]{4}

    - any 4 digits
  • $

    - end of line.


Another way is to use negative viewing:

^(?!12)[0-9]{6}$

      

See another demo . There is (?!12)

no match here if the first 2 digits 12

. [0-9]{6}

will match 6 digits.

Depending on the library / regex method, the ^

/ bindings $

may not be required. Lookaheads are not always supported either.

+5


source







All Articles