Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for 1st alphabat letter, numbers and alphabat in parentheses

Tags:

regex

I'm trying to write my first regular expression.. I'm having value of the following combinations

letters [upper or lowercase]
numbers [0-9]
letters in parentheses [(M)]
no spaces or other characters

a few examples:

OK: "A3"
OK: "N15"
OK: "A126"
OK: "B6469"
OK: "A57(M)"
OK: "A1(M)"

NOT OK: "TF9 3TF"
NOT OK: "B64 69"

My Regular Exp:

^(([a-zA-Z][1-9]\([a-zA-Z]\)?)|([a-zA-Z][1-9][1-9]\([a-zA-Z]\)?)|([a-zA-Z][1-9]?)|([a-zA-Z][1-9][1-9]?)|([a-zA-Z][1-9][1-9][1-9]?)|([a-zA-Z][1-9][1-9][1-9][1-9]?))$

its works fine for me. but i want best solution for it, like my regular expression seems to be too long because for each combination i make a expression and then combine all these but i want to reduce my regular expression like in my sample code contain first alphabet then number that can be one or more but up till 5. tell me how can i make one expression that will work for (A1, A12, A123, A1234, A12345)?

like image 270
ARsl Avatar asked Jun 27 '13 10:06

ARsl


1 Answers

That does seem overly complex.

^[a-zA-Z]\d{1,5}(?:\(M\))?$

Should do it.

like image 184
Niet the Dark Absol Avatar answered Oct 03 '22 02:10

Niet the Dark Absol