gurarach
gurarach

Reputation: 21

Regex variable length

I am looking for a regex that matches:

Length is between 1 and 10.
The 8th character can be alphanumeric [0-9a-zA-Z] and the rest have to be digits [0-9]

Valid

1
123
1234567890
1234567a

Invalid

1a
123456789a
12345678901

I have tried: [0-9]{1,7}[0-9a-zA-Z][0-9]{0,1} but that is failing miserably

Upvotes: 1

Views: 1547

Answers (3)

The fourth bird
The fourth bird

Reputation: 163632

You can match either 1-7 digits, or match 7 digits, the 8th one being [0-9a-zA-Z] and optional 2 digits.

^(?:\d{7}[\da-zA-Z]\d{0,2}|\d{1,7})$
  • ^ Start of string
  • (?: Non capture group
    • \d{7}[\da-zA-Z]\d{0,2} Match 7 digits and one of 0-9a-zA-Z] and 2 optional digits
    • | Or
    • \d{1,7} Match 1-7 digits
  • ) Close non capture group
  • $ End of string

Regex demo

Upvotes: 4

JvdV
JvdV

Reputation: 75990

You could try:

^(?!.{11})\d(?:\d{6}[^\W_])?\d*$

See an online demo


  • ^ - Start-line anchor;
  • (?!.{11}) - Negative lookahead to prevent 11 chars;
  • \d - A single digit;
  • (?:\d{6}[^\W_])? - Optional non-capture group to match 6 more digits and any character in class [A-Za-z0-9];
  • \d* - 0+ (Greedy) digits;
  • $ - End-line anchor.

Upvotes: 2

b3z
b3z

Reputation: 189

Well you could simplify The fourth birds solution by using \w

Like so:

^(?:\d{7}\w\d{0,2}|\d{1,7})$

But that’s basically the same.

Upvotes: 0

Related Questions