import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)
Answer from CrazyCasta on Stack Overflow
๐ŸŒ
Plain English Westminster
benhoyt.com โ€บ writings โ€บ python-pattern-matching
Structural pattern matching in Python 3.10
Python evaluates the match expression, and then tries each case from the top, executing the first one that matches, or the _ default case if no others match. But hereโ€™s where the structural part comes in: the case patterns donโ€™t just have to be literals.
Discussions

Structural Pattern Matching Should Permit Regex String Matches - Ideas - Discussions on Python.org
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+': ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
January 11, 2023
Matching a list of regex to every string in a list one by one
I have a list of strings and a list of regex patterns. What I want to achieve is that for every string in the list, I want to try matching the patterns found in the regex list that I have created. As soon as a match is found, I want to no longer look in the regex list for further matches. More on forum.freecodecamp.org
๐ŸŒ forum.freecodecamp.org
1
0
November 2, 2022
Regex vs normal string matching/what are you supposed to use regex for?
Regex is much more flexible. It is used for finding patterns, not just static strings. For instance, the regex to match any email address is [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@ (?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? Regex are pretty complicated, and I would only reach for one if I really needed it. But my buddy is fluent in them, so he uses them all the time. More on reddit.com
๐ŸŒ r/learnpython
19
12
January 7, 2015
Regular Expressions (RE) Module - Search and Match Comparison
Hello, I have a question regarding the regular expression compile. I created a code snippet to compare the different search and match results using different strings and using different patterns. Here is the test code snippet: import re s1 = 'bob has a birthday on Feb 25th' s2 = 'sara has a ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
October 26, 2023
๐ŸŒ
Python
peps.python.org โ€บ pep-0636
PEP 636 โ€“ Structural Pattern Matching: Tutorial | peps.python.org
Until now, the only non-simple pattern we have experimented with is the sequence pattern. Each element in a sequence pattern can in fact be any other pattern. This means that you could write a pattern like ["first", (left, right), _, *rest]. This ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ pattern-matching-python-regex
Pattern matching in Python with Regex - GeeksforGeeks
January 19, 2026 - Pattern matching in Python allows you to search, extract, and validate text using regular expressions. Regex provides a flexible way to work with strings based on defined patterns.
๐ŸŒ
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...
๐ŸŒ
Martin Heinz
martinheinz.dev โ€บ blog โ€บ 78
Recipes and Tricks for Effective Structural Pattern Matching in Python | Martin Heinz | Personal Website & Blog
August 2, 2022 - Common use case for match/case is efficient matching of JSON structures in form of Python's dictionaries. This can be done with mapping pattern which is triggered by case {...}: ...
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-check-if-a-string-matches-regex-list
Python - Check if a string matches regex list
August 2, 2023 - By using the list comprehension without iterating over the regex list, we can create a new list containing the matching patterns. In this example, we are using the list comprehension with the line of code [pattern for pattern in regex_list if re.search(pattern, string)] which creates a new list matching_patterns that contains the regex patterns from regex_list that match the string.
๐ŸŒ
DEV Community
dev.to โ€บ sk_rajibul_9ce58a68c43bb5 โ€บ mastering-efficient-string-matching-techniques-in-python-using-regex-2m23
Mastering Efficient String Matching Techniques in Python using regex - DEV Community
April 7, 2024 - Anchors such as ^ and $ can be combined with quantifiers to match patterns at the beginning or end of a string. Example: pattern = "^ab+c$" will match strings that start with "a", followed by one or more "b"s, and end with "c".
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ regex vs normal string matching/what are you supposed to use regex for?
r/learnpython on Reddit: Regex vs normal string matching/what are you supposed to use regex for?
January 7, 2015 -

Hiya;

Part of a project I'm doing involves reading 200k+ line csv files and using keywords to filter those lines into different types of messages which will then be examined further

I was reading up on how to do this, and the regular expression re module appeared to be the way forward. however I did some testing comparing the re.match function to the is this string in that string function, and the former was several times slower. If Regex is so much slower than normal string matching, why/when should you use it/ or did I use regex wrong and its actually much faster?

results:

regex: 275.0342330016417

normal string matching: 44.675843185239046

test code:

import random
import re
from timeit import timeit

alp_str="abcdefghijklmnopqrstuvwxyz"


result=[]
counter=200000
while counter > 0:
    example=""
    length=50
    while length > 0:
        example+=(alp_str[random.randrange(25)])
        length-=1
    result.append(example)
    counter-=1

text='search'

def re_find(strings, text):
    num=0
    for string in strings:
        num+=1
        if re.match(text, string):
            pass

def best_find(strings, text):
    num=0
    for string in strings:
        num+=1
        if text in string:
            pass



print (timeit("re_find(result, text)","from __main__ import re_find;from __main__ import result;from __main__ import text",number=1000))  
print (timeit("best_find(result, text)","from __main__ import best_find;from __main__ import result;from __main__ import text",number=1000))
Top answer
1 of 4
9
Regex is much more flexible. It is used for finding patterns, not just static strings. For instance, the regex to match any email address is [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@ (?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? Regex are pretty complicated, and I would only reach for one if I really needed it. But my buddy is fluent in them, so he uses them all the time.
2 of 4
4
regex is crazy fast, but in is really fast as well, so it should be a good race. If you lengthen the search string or the string to be searched for you might see slightly differing results. But generally there is no good reason to use regex if a simple in would work in its place. You probably want to use regex only if you were searching for a more complex pattern. That said, you could make your code a bit faster, see my suggestions below: import random import re from timeit import timeit alp_str="abcdefghijklmnopqrstuvwxyz" result=[] counter=200000 counter=20 s_l = 100 s_l = 100000 while counter > 0: example="".join(random.choice(alp_str) for _ in range(s_l)) result.append(example) counter-=1 def re_find(strings, text): num=0 # I put in re.compile here because it should speed up things a bit. This # prevents recompiling the regex each time. Note that regex caches # compilations, so that probably has less of an impact than your would # expect. # Putting it in here should prevent global namespace # lookups in the loop, which ought to give you more of a boost than just not # recompiling -- which in any event it probably was not doing # so the next line can be used just to stuff it into the namespace #x = re.search # this both stuffs it into the func's namespace, and also compiles x = re.compile(text) for string in strings: # i think you want search (find anywhere in string) versus match (find # only at the begining) if x.search(string): #if re.search(text, string): #if x(text, string): num+=1 pass return num def best_find(strings, text): num=0 for string in strings: if text in string: num+=1 return num print('result built') print(len(result)) print(len(result[0])) # short test string that should return a bunch of matches #text='ab' # longer string that will probably return few matches -- so you can test miss # speed as well as hit speed text = 'longer' print('with regex') print(re_find(result, text)) print (timeit("re_find(result, text)","from __main__ import re_find;from __main__ import result;from __main__ import text",number=1000)) print('with in') print(best_find(result, text)) print (timeit("best_find(result, text)","from __main__ import best_find;from __main__ import result;from __main__ import text",number=1000))
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ re.html
re โ€” Regular expression operations
4 days ago - 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-...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ regex.html
Regular Expression HOWTO โ€” Python 3.14.3 documentation
Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Regular Expressions (RE) Module - Search and Match Comparison - Python Help - Discussions on Python.org
October 26, 2023 - Hello, I have a question regarding the regular expression compile. I created a code snippet to compare the different search and match results using different strings and using different patterns. Here is the test code snippet: import re s1 = 'bob has a birthday on Feb 25th' s2 = 'sara has a birthday on March 3rd' s3 = '12eup 586iu' s4 = '0turt' # '\w\w\w \d\d\w\w' bday1_re = re.compile('\w+ \d+\w+') # Also tried: '\w+ \d+\w+' bday2_re = re.comp...
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python regular expressions
Python Regular Expressions | Python Education | Google for Developers
Regular expressions are used for matching text patterns in Python using the re module. The re.search(pat, str) function searches for a pattern in a string and returns a match object if found, or None otherwise.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_match.asp
Python Match
Remove List Duplicates Reverse ... Python Certificate Python Training ... The match statement is used to perform different actions based on different conditions....
๐ŸŒ
Real Python
realpython.com โ€บ structural-pattern-matching
Structural Pattern Matching in Python โ€“ Real Python
August 6, 2024 - The match statement takes a subject, which can be any valid Python expression, such as a string literal or a function call, and compares the resulting value to one or more patterns listed in the case clauses.
๐ŸŒ
LeetCode
leetcode.com โ€บ problems โ€บ regular-expression-matching
Regular Expression Matching - LeetCode
Can you solve this real interview question? Regular Expression Matching - Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: * '.' Matches any single character. * '*' Matches zero or more of the preceding element.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ regex-regular-expressions
Mimo: The coding platform you need to learn Web Development, Python, and more.
Start your coding journey with Python. Learn basics, data types, control flow, and more ... It's best practice to define regex patterns using raw strings by prefixing the string with an r (e.g., r"\d+") to prevent backslashes from being misinterpreted. 1. Finding the First Match with re.search(): This function returns a match object if the pattern is found, and None otherwise.
๐ŸŒ
Regex101
regex101.com
regex101: build, test, and debug regex
Regular expression tester with syntax highlighting, explanation, cheat sheet for PHP/PCRE, Python, GO, JavaScript, Java, C#/.NET, Rust.
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Regular_expression
Regular expression - Wikipedia
5 days ago - When entering a regex in a programming language, they may be represented as a usual string literal, hence usually quoted; this is common in C, Java, and Python for instance, where the regex re is entered as "re". However, they are often written with slashes as delimiters, as in /re/ for the regex re. This originates in ed, where / is the editor command for searching, and an expression /re/ can be used to specify a range of lines (matching the pattern), which can be combined with other commands on either side, most famously g/re/p as in grep ("global regex print"), which is included in most Unix-based operating systems, such as Linux distributions.