import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
Answer from CrazyCasta on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations — Python 3.14.3 ...
Source code: Lib/re/ This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings ( str) as well as 8-...
🌐
W3Schools
w3schools.com › python › python_regex.asp
Python RegEx
Python has a built-in package called re, which can be used to work with Regular Expressions. ... You can add flags to the pattern when using regular expressions. A special sequence is a \ followed by one of the characters in the list below, ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › pattern-matching-python-regex
Pattern matching in Python with Regex - GeeksforGeeks
June 28, 2017 - The (wo)? part of the regular expression means that the pattern wo is an optional group. The regex will match text that has zero instances or one instance of wo in it. This is why the regex matches both 'Batwoman' and 'Batman'. You can think of the ? as saying,groups “Match zero or one of the group preceding this question mark.” If you need to match an actual question mark character, escape it with \?. ... # Python program to illustrate # optional matching # with question mark(?) import re batRegex = re.compile(r'Bat(wo)?man') mo1 = batRegex.search('The Adventures of Batman') mo2 = batRegex.search('The Adventures of Batwoman') print(mo1.group()) print(mo2.group())
🌐
Python documentation
docs.python.org › 3 › howto › regex.html
Regular Expression HOWTO — Python 3.14.3 documentation
>>> print(re.match(r'From\s+', ... 5), match='From '> Under the hood, these functions simply create a pattern object for you and call the appropriate method on it....
Top answer
1 of 7
29

Update

I condensed this answer into a python package to make matching as easy as pip install regex-spm,

import regex_spm

match regex_spm.fullmatch_in("abracadabra"):
  case r"\d+": print("It's all digits")
  case r"\D+": print("There are no digits in the search string")
  case _: print("It's something else")

Original answer

As Patrick Artner correctly points out in the other answer, there is currently no official way to do this. Hopefully the feature will be introduced in a future Python version and this question can be retired. Until then:

PEP 634 specifies that Structural Pattern Matching uses the == operator for evaluating a match. We can override that.

import re
from dataclasses import dataclass

# noinspection PyPep8Naming
@dataclass
class regex_in:
    string: str

    def __eq__(self, other: str | re.Pattern):
        if isinstance(other, str):
            other = re.compile(other)
        assert isinstance(other, re.Pattern)
        # TODO extend for search and match variants
        return other.fullmatch(self.string) is not None

Now you can do something like:

match regex_in(validated_string):
    case r'\d+':
        print('Digits')
    case r'\s+':
        print('Whitespaces')
    case _:
        print('Something else')

Caveat #1 is that you can't pass re.compile'd patterns to the case directly, because then Python wants to match based on class. You have to save the pattern somewhere first.

Caveat #2 is that you can't actually use local variables either, because Python then interprets it as a name for capturing the match subject. You need to use a dotted name, e.g. putting the pattern into a class or enum:

class MyPatterns:
    DIGITS = re.compile('\d+')

match regex_in(validated_string):
    case MyPatterns.DIGITS:
        print('This works, it\'s all digits')

Groups

This could be extended even further to provide an easy way to access the re.Match object and the groups.

# noinspection PyPep8Naming
@dataclass
class regex_in:
    string: str
    match: re.Match = None

    def __eq__(self, other: str | re.Pattern):
        if isinstance(other, str):
            other = re.compile(other)
        assert isinstance(other, re.Pattern)
        # TODO extend for search and match variants
        self.match = other.fullmatch(self.string)
        return self.match is not None

    def __getitem__(self, group):
        return self.match[group]

# Note the `as m` in in the case specification
match regex_in(validated_string):
    case r'\d(\d)' as m:
        print(f'The second digit is {m[1]}')
        print(f'The whole match is {m.match}')
2 of 7
23

Clean solution

There is a clean solution to this problem. Just hoist the regexes out of the case-clauses where they aren't supported and into the match-clause which supports any Python object.

The combined regex will also give you better efficiency than could be had by having a series of separate regex tests. Also, the regex can be precompiled for maximum efficiency during the match process.

Example

Here's a worked out example for a simple tokenizer:

pattern = re.compile(r'(\d+\.\d+)|(\d+)|(\w+)|(".*)"')
Token = namedtuple('Token', ('kind', 'value', 'position'))
env = {'x': 'hello', 'y': 10}

for s in ['123', '123.45', 'x', 'y', '"goodbye"']:
    mo = pattern.fullmatch(s)
    match mo.lastindex:
        case 1:
            tok = Token('NUM', float(s), mo.span())
        case 2:
            tok = Token('NUM', int(s), mo.span())
        case 3:
            tok = Token('VAR', env[s], mo.span())
        case 4:
            tok = Token('TEXT', s[1:-1], mo.span())
        case _:
            raise ValueError(f'Unknown pattern for {s!r}')
    print(tok) 

This outputs:

Token(kind='NUM', value=123, position=(0, 3))
Token(kind='NUM', value=123.45, position=(0, 6))
Token(kind='VAR', value='hello', position=(0, 1))
Token(kind='VAR', value=10, position=(0, 1))
Token(kind='TEXT', value='goodbye', position=(0, 9))

Better Example

The code can be improved by writing the combined regex in verbose format for intelligibility and ease of adding more cases. It can be further improved by naming the regex sub patterns:

pattern = re.compile(r"""(?x)
    (?P<float>\d+\.\d+) |
    (?P<int>\d+) |
    (?P<variable>\w+) |
    (?P<string>".*")
""")

That can be used in a match/case statement like this:

for s in ['123', '123.45', 'x', 'y', '"goodbye"']:
    mo = pattern.fullmatch(s)
    match mo.lastgroup:
        case 'float':
            tok = Token('NUM', float(s), mo.span())
        case 'int':
            tok = Token('NUM', int(s), mo.span())
        case 'variable':
            tok = Token('VAR', env[s], mo.span())
        case 'string':
            tok = Token('TEXT', s[1:-1], mo.span())
        case _:
            raise ValueError(f'Unknown pattern for {s!r}')
    print(tok)

Comparison to if/elif/else

Here is the equivalent code written using an if-elif-else chain:

for s in ['123', '123.45', 'x', 'y', '"goodbye"']:
    if (mo := re.fullmatch('\d+\.\d+', s)):
        tok = Token('NUM', float(s), mo.span())
    elif (mo := re.fullmatch('\d+', s)):
        tok = Token('NUM', int(s), mo.span())
    elif (mo := re.fullmatch('\w+', s)):
        tok = Token('VAR', env[s], mo.span())
    elif (mo := re.fullmatch('".*"', s)):
        tok = Token('TEXT', s[1:-1], mo.span())
    else:
        raise ValueError(f'Unknown pattern for {s!r}')
    print(tok)

Compared to the match/case, the if-elif-else chain is slower because it runs multiple regex matches and because there is no precompilation. Also, it is less maintainable without the case names.

Because all the regexes are separate we have to capture all the match objects separately with repeated use of assignment expressions with the walrus operator. This is awkward compared to the match/case example where we only make a single assignment.

🌐
Google
developers.google.com › google for education › python › python regular expressions
Python Regular Expressions | Python Education | Google for Developers
In Python a regular expression search is typically written as: ... The re.search() method takes a regular expression pattern and a string and searches for that pattern within the string.
🌐
Python.org
discuss.python.org › ideas
Structural Pattern Matching Should Permit Regex String Matches - Ideas - Discussions on Python.org
January 11, 2023 - I want to be able to match cases in a match statement against different regular expression strings. Essentially, I would like to be able to do something like what is described in this StackOverflow issue in python: match regex_in(some_string): case r'\d+': print('Digits') case r'\s+': print('Whitespaces') case _: print('Something else') The above syntax is just an example taken from the SO post - I don’t have strong feelings about what exactly it should look...
Find elsewhere
🌐
QA Touch
qatouch.com › home › python regex testing: a comprehensive guide with examples
Python Regex Testing: A Comprehensive Guide with Examples
June 24, 2025 - Step 1: Import the re Module To use regex in Python, you need to import the built-in re module: Step 2: Define the Regex Pattern Identify the pattern you want to match or search for within a string.
🌐
PYnative
pynative.com › home › python › regex › python regex match: a comprehensive guide for pattern matching
Python Regex Match: A Comprehensive guide for pattern matching
April 2, 2021 - import re target_string = "Emma ... · As you can see, the match starts at index 0 and ends before index 4. because the re.match() method always performance pattern matching at the beginning of the target string....
🌐
TutorialsPoint
tutorialspoint.com › pattern-matching-in-python-with-regex
Pattern matching in Python with Regex
Each pattern matched is represented by a tuple and each tuple contains group(1), group(2).. data. ... import re regex = r'([\w\.-]+)@([\w\.-]+)' str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com') matches = re.findall(regex, str) print(matches) for tuple in matches: print("Username: ",tuple[0]) #username print("Host: ",tuple[1]) #host
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 2e › chapter7
Chapter 7 – Pattern Matching with Regular Expressions
Regular expressions, called regexes for short, are descriptions for a pattern of text. For example, a \d in a regex stands for a digit character—that is, any single numeral from 0 to 9. The regex \d\d\d-\d\d\d-\d\d\d\d is used by Python to match the same text pattern the previous isPhoneNumber() ...
🌐
Programiz
programiz.com › python-programming › regex
Python RegEx (With Examples)
Python has a module named re to work with regular expressions. To use it, we need to import the module. ... The module defines several functions and constants to work with RegEx. The re.findall() method returns a list of strings containing all matches. # Program to extract numbers from a string ...
🌐
Medium
medium.com › @23saini › power-of-pattern-matching-python-regex-7ee62284f7a3
Power of Pattern Matching- Python RegEx | by Neha Saini | Medium
July 8, 2023 - Learn how to use Python regular expressions (RegEx) to match patterns and extract information from text easily. This beginner-friendly guide provides examples and step-by-step explanations for…
🌐
StrataScratch
stratascratch.com › blog › mastering-python-regex-a-deep-dive-into-pattern-matching
Mastering Python RegEx: A Deep Dive into Pattern Matching - StrataScratch
July 21, 2023 - Next, we’ll use the re.match() function. Here we will check whether the string text starts with the word "Python" or not. Then we’ll print the result to the console. Here is the code. import re pattern = "Python" text = "Python is amazing." # Check if the text starts with 'Python' match = re.match(pattern, text) # Output the result if match: print("Match found:", match.group()) else: print("No match found")
🌐
Automate the Boring Stuff
automatetheboringstuff.com › 3e › chapter9.html
Chapter 9 - Text Pattern Matching with Regular Expressions, Automate the Boring Stuff with Python, 3rd Ed
For example, the characters \d in a regex stand for a decimal numeral between 0 and 9. Python uses the regex string r'\d\d\d-\d\d\d-\d\d\d\d' to match the same text pattern the previous is_phone_number() function did: a string of three numbers, a hyphen, three more numbers, another hyphen, ...
🌐
Real Python
realpython.com › regex-python
Regular Expressions: Regexes in Python (Part 1) – Real Python
October 21, 2023 - The pattern matching here is still just character-by-character comparison, pretty much the same as the in operator and .find() examples shown earlier. The match object helpfully tells you that the matching characters were '123', but that’s not much of a revelation since those were exactly the characters you searched for. You’re just getting warmed up. ... The real power of regex matching in Python emerges when <regex> contains special characters called metacharacters.
🌐
Plain English Westminster
benhoyt.com › writings › python-pattern-matching
Structural pattern matching in Python 3.10
This is a shorthand to avoid specifying ... class pattern. One thing to note is that match and case are not real keywords but “soft keywords”, meaning they only operate as keywords in a match ... case block. This is by design, because people use match as a variable name all the time – I almost always use a variable named match as the result of a regex ...
🌐
Built In
builtin.com › articles › python-re-match
Python re.match() and re.sub() Explained | Built In
Python re.sub() is a function that’s used for substituting occurrences of a pattern in a string. It takes three main arguments: The pattern you want to replace, a regular expression.
🌐
Guru99
guru99.com › home › python › python regex: re.match(), re.search(), re.findall() with example
Python RegEx: re.match(), re.search(), re.findall() with Example
August 13, 2025 - re.match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string.