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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With