Check if string matches pattern


How do I check if a string matches this pattern?

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

Example, These would match:


These wouldn’t (‘^’ points to problem)

Asked By: DanielTA



import re
pattern = re.compile("^([A-Z][0-9]+)+$")
Answered By: CrazyCasta
import re
import sys

prog = re.compile('([A-Z]d+)+')

while True:
  line = sys.stdin.readline()
  if not line: break

  if prog.match(line):
    print 'matched'
    print 'not matched'
Answered By: Marc Cohen

regular expressions make this easy …

[A-Z] will match exactly one character between A and Z

d+ will match one or more digits

() group things (and also return things… but for now just think of them grouping)

+ selects 1 or more

Answered By: Joran Beasley
import re

ab = re.compile("^([A-Z]{1}[0-9]{1})+$")

I believe that should work for an uppercase, number pattern.

Answered By: Kneel-Before-ZOD

Please try the following:

import re

name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]

# Match names.
for element in name:
     m = re.match("(^[A-Z]d[A-Z]d)", element)
     if m:
Answered By: sumeet agrawal

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

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

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
Answered By: nehem

As stated in the comments, all these answers using re.match implicitly matches on the start of the string. is needed if you want to generalize to the whole string.

import re

pattern = re.compile("([A-Z][0-9]+)+")

# finds match anywhere in string
bool(, 'aA1A1'))  # True

# matches on start of string, even though pattern does not have ^ constraint
bool(re.match(pattern, 'aA1A1'))  # False

If you need the full string to exactly match the regex, see @Ali Sajjad’s answer using re.fullmatch

Credit: @LondonRob and @conradkleinespel in the comments.

Answered By: crypdick

Careful! (Maybe you want to check if FULL string matches)

The re.match(...) will not work if you want to match the full string.

For example;

  • re.match("[a-z]+", "abcdef") ✅ will give a match
  • But! re.match("[a-z]+", "abcdef 12345") ✅ will also give a match because there is a part in string which matches (maybe you don’t want that when you’re checking if the entire string is valid or not)


Use re.fullmatch(...). This will only match if the

if re.fullmatch("[a-z]+", my_string):
  • re.fullmatch("[a-z]+", "abcdef") ✅ Yes
  • re.fullmatch("[a-z]+", "abcdef 12345") ❌ No

One liner: bool(re.fullmatch("[a-z]+", my_string))

Answered By: Ali Sajjad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.