Search code examples
pythonregexstringstring-matching

Check if string matches pattern


How do I check if a string matches the following 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
    ^
    

Solution

  • import re
    pattern = re.compile("^([A-Z][0-9]+)+$")
    pattern.match(string)