394
votes

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
^
6
could you please explain more why it is a problem?John Woo
^([A-Z]\d+){1,}$ like this?Passerby
In your third example, the problem should be with B and not with A.Burhan Khalid
maybe it's a typo error on the problem. both A and B are small letters right? A10b and aB400?John Woo
@Burhan, The problem is with A because B has numbers next to it and A doesn'tDanielTA

6 Answers

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

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
43
votes

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:
        print(m.groups())
26
votes
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'
  else:
    print 'not matched'
9
votes
  
import re

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


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

8
votes

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