Python regex to match alphanumeric starting with capital letter and length range

Viewed 60

I need to match strings like these:

NEV2297075
WB/03/001/585269
WB/03/HK/585065

It should start with 2 or more capital letters and end with a number, can contain A-Z,/ and numbers in between and total length should be between 10 and 22

For this I used:

re.findall(r'[A-Z]{2,}[A-Z\/0-9]{1,}[0-9]{10,22}'

I see that the length range is applying to the expression immediately preceding it. How to apply length range to entire string?

1 Answers

The quantifier here [0-9]{10,22} repeats matching 10 - 22 digits.

If you want to verify the number of total characters, you should anchor the string and verify the number of characters until the next anchor using a lookahead ^(?=[A-Z\d,/]{10,22}$)

^(?=[A-Z\d,/]{10,22}$)[A-Z]{2,}[A-Z\d,/]*\d$

Regex demo

Related