506

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
^
5
  • 4
    could you please explain more why it is a problem?
    – John Woo
    Sep 26, 2012 at 5:29
  • 5
    ^([A-Z]\d+){1,}$ like this?
    – Passerby
    Sep 26, 2012 at 5:30
  • 3
    In your third example, the problem should be with B and not with A. Sep 26, 2012 at 5:33
  • maybe it's a typo error on the problem. both A and B are small letters right? A10b and aB400?
    – John Woo
    Sep 26, 2012 at 5:34
  • @Burhan, The problem is with A because B has numbers next to it and A doesn't
    – DanielTA
    Sep 26, 2012 at 5:39

9 Answers 9

657
import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
5
  • 66
    From the docs on re.match: If zero or more characters at the beginning of string match the regular expression pattern. I just spent like 30 minutes trying to understand why I couldn't match something at the end of a string. Seems like it's not possible with match, is it? For that, re.search(pattern, my_string) works though. Nov 11, 2016 at 15:52
  • 4
    @conradk Yes, you're right, I think there's something like an implied ^ at the beginning when you use match. I think it's a bit more complicated then that very simple explanation, but I'm not clear. You are correct that it does start from the beginning of the string though.
    – CrazyCasta
    Nov 11, 2016 at 20:10
  • I edited your answer, because it only makes sense with search() in this context.
    – Robo Robok
    Feb 21, 2021 at 12:16
  • Yes, but that's what the questioner wants. I'm not sure what you mean by "only makes sense with search()". It works perfectly fine with match.
    – CrazyCasta
    Sep 5, 2021 at 21:03
  • To be clear: You probably want to check if pattern.match returns something; luckily "None" is truthy, so you can just do "if pattern.match:" Jun 22, 2022 at 19:59
343

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
7
  • 1
    That's weird. Why can you use re.match in the context of an if, but you have to use bool if you're using it elsewhere?
    – LondonRob
    Mar 13, 2018 at 13:59
  • 62
    Careful with re.match. It only matches at the start of a string. Have a look at re.search instead.
    – LondonRob
    Mar 13, 2018 at 14:02
  • 3
    @LondonRob probably because if checks for the match not being None.
    – Dennis
    Mar 18, 2019 at 13:17
  • 2
    @SuhFangmbeng Compilation is useful when the same re is used in more than one places to improve efficiency. In terms of error .match would throw the same error what .compile does. It's perfectly safe to use.
    – nehem
    May 6, 2020 at 21:58
  • 2
    @nehem actually all of the regex functions in re module compile and cache the patterns. Therefore there is absolutely no efficiency gain using compile and then match than just directly calling re.match. All of these functions call the internal function _compile (including re.compile) which does the caching to a python dictionary.
    – miksus
    Jun 29, 2021 at 21:12
55

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())
2
  • 1
    This is the only case that returns the match which is required for getting groups. Best answer in my opinion.
    – Rick Smith
    Dec 12, 2016 at 20:59
  • best answer among other answers
    – CK5
    Jun 3, 2022 at 11:16
31
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'
19

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

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.

12

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

12
  
import re

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


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

0
9

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)

Solution

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

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

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

1
  • Thanks. This is exactly what I wanted to see for "check if string matches"
    – mishadr
    Oct 11, 2022 at 16:56
0

Ali Sajjad's answer should be the default, i.e. fullmatch to avoid false positives.

However, it's also important to know that you're always checking not None for "yes, it's a match":

The two possibilities are therefore:

if re.fullmatch("[a-z]+", my_string)!=None:

or, as in Ali's answer:

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

To my way of thinking both of these are really quite horribly unreadable. So a simple utility function is needed for readability:

def is_match(pattern, string, flags=re.IGNORECASE | re.DOTALL): # or "is_full_match", as desired
    return re.fullmatch(pattern, string, flags)!=None

Those 2 flags are (usually) the most helpful default flags settings in my experience, rather than "0".

In practice, of course, you may need to examine the Match object delivered by re.fullmatch. But for cases where you just need to find whether there's a match...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.