Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx pattern any two letters followed by six numbers

Tags:

regex

Please assist with the proper RegEx matching any 2 letters followed by any combination of 6 whole numbers.

These would be valid:  RJ123456 PY654321 DD321234  These would not DDD12345 12DDD123 
like image 801
Fergus Avatar asked May 03 '12 21:05

Fergus


People also ask

How do I allow only letters and numbers in regex?

In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".

What is a regex give an example of a regex pattern?

A regex (regular expression) consists of a sequence of sub-expressions. In this example, [0-9] and + . The [...] , known as character class (or bracket list), encloses a list of characters. It matches any SINGLE character in the list.

How do I match a pattern in regex?

Regular expressions, called regexes for short, are descriptions for a pattern of text. For example, a \d in a regex stands for a digit character — that is, any single numeral 0 to 9. Following regex is used in Python to match a string of three numbers, a hyphen, three more numbers, another hyphen, and four numbers.

What regex syntax is used for matching any number of repetitions?

A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.


2 Answers

[a-zA-Z]{2}\d{6}

[a-zA-Z]{2} means two letters \d{6} means 6 digits

If you want only uppercase letters, then:

[A-Z]{2}\d{6}

like image 136
Israel Unterman Avatar answered Sep 18 '22 22:09

Israel Unterman


You could try something like this:

[a-zA-Z]{2}[0-9]{6} 

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below                # A character in the range between “a” and “z”                # A character in the range between “A” and “Z”    {2}         # Exactly 2 times [0-9]       # Match a single character in the range between “0” and “9”    {6}         # Exactly 6 times 

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$ 

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b 

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6} 
like image 33
Robbie Avatar answered Sep 21 '22 22:09

Robbie