python – Check if string matches pattern

The Question :

349 people think this question is useful

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)


The Question Comments :
  • could you please explain more why it is a problem?
  • ^([A-Z]\d+){1,}$ like this?
  • In your third example, the problem should be with B and not with A.
  • maybe it’s a typo error on the problem. both A and B are small letters right? A10b and aB400?
  • @Burhan, The problem is with A because B has numbers next to it and A doesn’t

The Answer 1

509 people think this answer is useful
import re
pattern = re.compile("^([A-Z][0-9]+)+$")

Edit: As noted in the comments match checks only for matches at the beginning of the string while will match a pattern anywhere in string. (See also:

The Answer 2

209 people think this answer is useful

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'))

The Answer 3

40 people think this answer is useful

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:

The Answer 4

25 people think this answer is useful
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'

The Answer 5

8 people think this answer is useful
import re

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

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

The Answer 6

7 people think this answer is useful

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

Add a Comment