Check if string matches pattern

Posted on

Question :

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:

A1B2
B10L1
C1N200J1

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

a1B2
^
A10B
   ^
AB400
^
Asked By: DanielTA

||

Answer #1:

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

Edit: As noted in the comments match checks only for matches at the beginning of the string while re.search() will match a pattern anywhere in string. (See also: https://docs.python.org/library/re.html#search-vs-match)

Answered By: CrazyCasta

Answer #2:

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
Answered By: nehem

Answer #3:

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())
Answered By: sumeet agrawal

Answer #4:

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'
Answered By: Marc Cohen

Answer #5:

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

Answer #6:

  
import re

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

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

Answered By: Kneel-Before-ZOD

Leave a Reply

Your email address will not be published. Required fields are marked *