Reputation: 3716
I need a regex for the following pattern:
Total of 5 characters (alpha and numeric, nothing else).
first character must be a letter (A
, B
, or C
only)
the remaining 4 characters can be number or letter.
Clarifcation: the first letter can only be A
, B
, or C
.
Examples:
A1234
is validD1234
is invalidUpvotes: 31
Views: 83938
Reputation: 31845
EDIT: Grrr... edited regex due to new "clarification" :)
^[A-C][a-zA-Z0-9]{4}$
EDIT: To explain the above Regex in English...
^
and $
mean "From start to finish" (this ensures that the whole string must perfectly match)
[A-C]
means "Match either A
, B
, or C
"
[a-zA-Z0-9]{4}
means "Match 4 lower case letters, upper case letters, or numbers"
Upvotes: 55
Reputation:
This answer is correct, but I did want to add that you can shorten it a bit with the following.
^[A-C]\w{4}$
\w means any alphaNumeric character.
Upvotes: 1
Reputation: 1067
Something along the lines of:
[A-C][A-Za-z0-9]{4}
I would advise taking a look at http://regexlib.com/CheatSheet.aspx if you are unfamiliar with regular expressions and try to do these kind of simple regexs yourself.
There is also plenty of online regex testing apps such as: http://regexlib.com/RETester.aspx which enable you to test your regexes without writing any code.
Upvotes: 7
Reputation:
In case this is not Perl regexps we're talking about, some cut-and-paste is needed:
[ABC][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]
I cut-and-pasted "[a-zA-Z0-9]" four times.
Upvotes: 0
Reputation: 1726
Do you mean that the first letter must be an A, B or C? Or can it be any letter?
If it has to be an A,B,or C (case sensitive), then this would be the regular expression.
[A-C][a-zA-Z0-9]{4}
Otherwise, the other answers here suffice.
Upvotes: 3