eviljack
eviljack

Reputation: 3716

regex matching alpha character followed by 4 alphanumerics

I need a regex for the following pattern:

Clarifcation: the first letter can only be A, B, or C.

Examples:

Upvotes: 31

Views: 83938

Answers (6)

Timothy Khouri
Timothy Khouri

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

Gabe
Gabe

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

Brad Gilbert
Brad Gilbert

Reputation: 34120

/[ABC](?i:[a-z0-9]{4})/

Upvotes: 0

Martin
Martin

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

user3458
user3458

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

Carl
Carl

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

Related Questions