gantoine
gantoine

Reputation: 1275

Regex of exact length that matches specific group of numbers

I'm looking to build a regex that matches the following group of numbers:

10xxxxxxx 
1116xxxxx 
143xxxxxx
146xxxxxx 
149xxxxxx
159xxxxxx
16xxxxxxx

(note the length is always 9)

where x is any digit. My best attempt yielded this:

/^1[01456][1369]*[6]*[0-9]$/

However, I can't get the length of the string to always be 9. Any ideas?

Edit: Maybe I wasn't clear enough, it needs to match those 7 cases, and ONLY those, inclusively and exclusively.

Upvotes: 0

Views: 471

Answers (4)

Sam
Sam

Reputation: 20486

Is this what you want?

^(?=[0-9]{9}$)(?:10|1116|143|146|149|159|16)

Demo


This starts by looking at the beginning of the string for exactly 9 digits using a positive lookahead anchored to the end of the string. Then we look for any of your 7 specific groups of numbers that the string can start with.

Upvotes: 1

Toto
Toto

Reputation: 91385

How about:

^1(?:[06]\d{2}|116|4[369]\d|59\d)\d{5}$

Upvotes: 3

alpha bravo
alpha bravo

Reputation: 7948

use this pattern

^1[01456](16|3\d|6\d|9\d|\d\d)\d{5}$

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You can use this regex:

/^1[01456][1369][0-9]{6}$/

Since 3 digits are already matched by first 3 patterns 1, [01456] and [1369] so last one must match exact 6 characters to enforce it a 9 digit input.

Upvotes: 0

Related Questions