You're making things a little more complicated than they should be here. You can use something like this:
/^[a-zA-Z]{2}-[0-9]{2}$/;
^
will match the beginning of the string and $
will match the end of the string.
This regex will allow only strings containing 2 letters, followed by one hyphen and followed by 2 digits. You can rewrite [0-9]
as \d
as well in javascript.
/([a-zA-Z]{2}(?!\b))((-){1})([0-9]{2}(?!\B))/;
This doesn't quite work as you might expect. (?!\b)
prevents a word boundary from occurring immediately after the 2 letters, which will make your valid strings fail.
((-){1})
You don't need so many parenthesis, even if you want to group those, because there's hardly anything to group. Use parentheses to capture stuff you'll use later on. The {1}
is redundant as well. I have never seen a single concrete use of {1}
. {n}
is useful when n
is greater than 1.
([0-9]{2}(?!\B))
Again, the parentheses are not quite useful, but here, you used a negated word boundary, which should work well (similar to $
but anywhere in the string).
If you want to match such format anywhere in a string, then you can use word boundaries as follows:
/\b[a-zA-Z]{2}-[0-9]{2}\b/;