I am writing a regular expression in which the string can be of 2-3 characters.
The first character has to be a Alphabet between A and H (capitals). This character has to be followed by a number between 1 and 12.
I wrote
[A-H]{1}[1-12]{1,2}
This is fine when I keyin A12 but not when I keyin A6
Please suggest.
You can’t specify a range of digits like that because it is implemented as a range between characters, so
[1-12]is equivalent to[12], which would only match either a1or a2. Instead, try the following:Here is an explanation:
Note that the
{1}after[A-H]in your original regex is unnecessary,[A-H]{1}and[A-H]are equivalent.You may want to consider adding anchors to the regex, otherwise you would also get a partial match on a string like
A20. If you are trying to match an entire string then you should use the following:If it is within a larger text you could use word boundaries instead: