I need a regular expression for which:
the string is alphanumeric and have exactly 6 characters in the first half followed by hyphen(optional) followed by optional 4 cha
^[a-zA-Z0-9]{6}-?[a-zA-Z0-9]{0,4}$
This isn't as concise as some of the others, but it is bulletproof. Tanascius' and Streetpc's solutions will match ______-____
, since \w
matches underscores.
One question: you say the dash is optional and the following four characters are optional, so does that mean 111111AAAA
should match? If so, my regex above is for you, since Tanascius' will not match this.
If this isn't the case, then you'll want this:
^[a-zA-Z0-9]{6}(?:-[a-zA-Z0-9]{1,4})?$
Which makes use of slightly more efficient backreferenceless grouping.
One last thing. This solution won't match 111111-
but will match 11111-A
. If you would like to match on 111111-
, but also don't want to match 111111A
, go with this:
^[a-zA-Z0-9]{6}(?:-[a-zA-Z0-9]{0,4})?$
EDIT: Tanascius' solution no longer uses \w
, so disregard what's said above concerning this.