Check if string matches pattern

DanielTA picture DanielTA · Sep 26, 2012 · Viewed 573.9k times · Source

How do I check if a string matches this pattern?

Uppercase letter, number(s), uppercase letter, number(s)...

Example, These would match:

A1B2
B10L1
C1N200J1

These wouldn't ('^' points to problem)

a1B2
^
A10B
   ^
AB400
^

Answer

CrazyCasta picture CrazyCasta · Sep 26, 2012
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)

Edit: As noted in the comments match checks only for matches at the beginning of the string while re.search() will match a pattern anywhere in string. (See also: https://docs.python.org/library/re.html#search-vs-match)