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
In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".
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.
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.
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.
[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}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With