Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex matching alpha character followed by 4 alphanumerics

Tags:

regex

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 valid
  • D1234 is invalid
like image 210
eviljack Avatar asked Dec 02 '08 14:12

eviljack


People also ask

How do you match a character sequence in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .

How do you escape a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

What regular expression that matches exactly sequence of a number a character and a special character joined with an underscore?

[a-zA-Z0-9_]+ Matches alpha-numeric character and underscore.


2 Answers

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"

like image 76
Timothy Khouri Avatar answered Sep 19 '22 15:09

Timothy Khouri


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.

like image 20
Martin Avatar answered Sep 18 '22 15:09

Martin