2

I've been stuck on this problem for days. I need a regex to validate an Id of this format:

^[0-9]{2}[-]{0,1}[0-9]{7}$

But from this pattern I have to exclude sets like:

  • 00-0000000 and 000000000
  • 11-1111111 and 111111111
  • 22-2222222 and 222222222
  • ...
  • 99-9999999 and 999999999

Note that 22-2222221 is valid.

Can anyone help me? If the Id is written without the dash, I could use ^(\d)(?!\1{8})\d{8}$ but what if the hyphen is present?

Tried something like

^(\d)(?!\1{8})\d{8}$|^(\d)(?!\1{2})\d{1}-(?!\1{7})\d{7}$

but the second part does not seem to work properly.

Thanks to Wiktor for the solution. How would you adapt it also for pattern below?

^[0-9]{3}[-]{0,1}[0-9]{2}[-]{0,1}[0-9]{4}$

Probably something like this can work: ^(?!(\d)(?:-?\1)*$)\d{3}-?\d{2}-?\d{4}$

despaolo
  • 23
  • 4
  • Maybe just check format with regex and then additionally check just by manually written code to exclude forbidden sets? It might not be an option, if you must do it in regex, but if otherwise, this approach might be even simpler and easier to read – Nikolay Dec 22 '22 at 09:35

1 Answers1

1

You can use

^(?!(\d)(?:-?\1)*$)\d{2}-?\d{7}$

See the regex demo.

Details:

  • ^ - start of string
  • (?!(\d)(?:-?\1)*$) - a negative lookahead that fails the match if there is
    • (\d) - a digit (captured in Group 1)
    • (?:-?\1)* - zero or more sequences of an optional - and then the digit that was captured in Group 2
    • $ - end of string, immediately to the right of the current location
  • \d{2}-?\d{7} - two digits, an optional -, and then seven digits
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563