Check if string matches pattern

PythonRegexString Matching

Python Problem Overview


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
^

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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'

Solution 5 - Python


import re




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

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


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

Solution 6 - Python

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

Solution 7 - Python

As stated in the comments, all these answers using re.match implicitly matches on the start of the string. re.search 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(re.search(pattern, 'aA1A1'))  # True

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

Credit: @LondonRob and @conradkleinespel in the comments.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanielTAView Question on Stackoverflow
Solution 1 - PythonCrazyCastaView Answer on Stackoverflow
Solution 2 - PythonnehemView Answer on Stackoverflow
Solution 3 - Pythonsumeet agrawalView Answer on Stackoverflow
Solution 4 - PythonMarc CohenView Answer on Stackoverflow
Solution 5 - PythonKneel-Before-ZODView Answer on Stackoverflow
Solution 6 - PythonJoran BeasleyView Answer on Stackoverflow
Solution 7 - PythoncrypdickView Answer on Stackoverflow