Check if string matches pattern

StackOverflow

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 rating: 551

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

Answer rating: 259

One-liner: re.match(r"pattern", string) # No need to compile

import re
>>> if re.match(r"hello[0-9]+", "hello1"):
...     print("Yes")
... 
Yes

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", "hello1"))
True




Get Solution for free from DataCamp guru