3


I am searching for a regex which cover this usecases:

  • The length of the string is 8
  • The first two characters "can" contain 1 digit, the rest of the 6 Charatcers are digits
  • Two digits at the beginning are not allowed

Examples:

  • AB123456 --> good
  • 1A789563 --> good
  • A2547896 --> good
  • 11111111 --> BAD

I tried with:

/^[a-zA-Z]{2}\d{6}$/

But this allow two digits at the beginning. Thank you for your help.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

3

You may use a "spelled-out" regex approach where you list all possible variations in a grouping construct with alternation operators:

^(?:[a-zA-Z][0-9]|[0-9][a-zA-Z]|[a-zA-Z]{2})[0-9]{6}$

Or, if your regex engine supports lookaheads

^(?![0-9]{2})[0-9a-zA-Z]{2}[0-9]{6}$

See the first regex demo and the second regex demo.

The ^ asserts the position at the start of the string, then the (?:[a-zA-Z][0-9]|[0-9][a-zA-Z]|[a-zA-Z]{2}) non-capturing group matches a letter + digit, digit + letter or just two letters. Then, [0-9]{6} matches 6 digits up to the end of the string ($).

The second regex matches the start of a string (^), then fails the match if the first two chars are digits ((?![0-9]{2})), then matches two alphnumeric chars ([0-9A-Za-z]{2}) and then six digits ([0-9]{6}), and asserts the position at the end of the string ($).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563