Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for fixed length string, starting with multiple words

Tags:

regex

I'm trying to make a regex (JS flavor) that matches a string that is exactly 17 alphanumeric characters in length and must start with either "AB, "DE" or "GH". After these 3 possibilities, any alphanumeric character is accepted.

Match:

AB163829F13246915
DET639601BA167860
GHF1973771A002957

Don't match

XYZ63829F13246915
AAA639601BA167860
BBC1973771A002957

So far I have this regex which I'm testing on http://regexpal.com/

^(AB|)[a-zA-Z0-9]{17}$

Not sure why the pipe character is required for it to match my first example, or why it fails when I add "DE" after the pipe.

Anyone?

like image 954
stef Avatar asked May 14 '13 16:05

stef


2 Answers

Use this:

^(AB|DE|GH)[a-zA-Z0-9]{15}$

The first two characters already take up two, so you only need 15 more alphanumeric characters after that.

http://rubular.com/r/rAWmIy4Xeh

like image 165
Explosion Pills Avatar answered Nov 15 '22 20:11

Explosion Pills


You had it almost:

(AB|DE|GH)[a-zA-Z0-9]{15}

Demo

Since AB|DE|GH will already be 2-char long, only 15 must be allowed beyond.

You can also use a non-capturing group ((?:AB|DE|GH)[a-zA-Z0-9]{15}) and anchor your pattern (^(?:AB|DE|GH)[a-zA-Z0-9]{15}$) if needed.

like image 36
sp00m Avatar answered Nov 15 '22 20:11

sp00m