🌐
W3Schools
w3schools.com › python › python_regex.asp
Python RegEx
RegEx can be used to check if a string contains the specified search pattern. Python has a built-in package called re, which can be used to work with Regular Expressions.
🌐
Python documentation
docs.python.org › 3 › howto › regex.html
Regular Expression HOWTO — Python 3.14.3 documentation
Let’s take an example: \w matches any alphanumeric character. If the regex pattern is expressed in bytes, this is equivalent to the class [a-zA-Z0-9_]. If the regex pattern is a string, \w will match all the characters marked as letters in ...
Discussions

Python: How to use RegEx in an if statement? - Stack Overflow
I have the following code which looks through the files in one directory and copies files that contain a certain string into another directory, but I am trying to use Regular Expressions as the st... More on stackoverflow.com
🌐 stackoverflow.com
[Python] How to get a RegEx code to grab a Stock Name using the Ticker
You've gotten the start of the name consistently, yes? So instead of [^\s]+ (meaning "get characters until a whitespace is found'), you can just use [^)]+ ('Get characters until a closing parenthesis is found') More on reddit.com
🌐 r/AskProgramming
6
1
December 31, 2020
Python re.sub() regex to substitute a character with a string except in quotes
The third-party regex module is useful for such cases: >>> import regex >>> s1 = '@ foo@ "abc@google.com"' >>> s2 = "@ foo@ 'abc@google.com'" >>> regex.sub(r'''(?:'[^']+'|"[^"]+")(*SKIP)(*F)|@''', 'bar', s1) 'bar foobar "abc@google.com"' >>> regex.sub(r'''(?:'[^']+'|"[^"]+")(*SKIP)(*F)|@''', 'bar', s2) "bar foobar 'abc@google.com'" Otherwise, you can use a custom function in the replacement section: >>> import re >>> s1 = '@ foo@ "abc@google.com"' >>> s2 = "@ foo@ 'abc@google.com'" >>> re.sub(r'''@|'[^']+'|"[^"]+"''', lambda m: 'bar' if m[0] == '@' else m[0], s1) 'bar foobar "abc@google.com"' >>> re.sub(r'''@|'[^']+'|"[^"]+"''', lambda m: 'bar' if m[0] == '@' else m[0], s2) "bar foobar 'abc@google.com'" More on reddit.com
🌐 r/regex
12
5
August 14, 2021
Help with RegEx on nested dictionary [Python 3]
It's a really common mistake to try to use regular expressions all the time where simple string operations are often faster, easier to write, more robust, and more readable. Here's a quick one-liner: dict([pair.split(' (') for pair in organization[:-1].split('), ')]) I'm sure you can write a working RE to solve this problem, but I don't think such a solution has much to recommend it really. More on reddit.com
🌐 r/learnpython
9
1
November 7, 2014
software library for interpreting regular expressions
Perl Compatible Regular Expressions (PCRE) is a library written in C, which implements a regular expression engine, inspired by the capabilities of the Perl programming language. Philip Hazel started writing PCRE in … Wikipedia
Factsheet
Original author Philip Hazel
Written in C
Operating system Cross-platform
Factsheet
Original author Philip Hazel
Written in C
Operating system Cross-platform
🌐
Wikipedia
en.wikipedia.org › wiki › Perl_Compatible_Regular_Expressions
Perl Compatible Regular Expressions - Wikipedia
January 8, 2026 - For example, (a|b)c\1 would match either "aca" or "bcb" and would not match, for example, "acb". A sub-pattern (surrounded by parentheses, like (...)) may be named by including a leading ?P<name> after the opening parenthesis. Named subpatterns are a feature that PCRE adopted from Python regular ...
🌐
DaniWeb
daniweb.com › programming › software-development › tutorials › 238544 › simple-regex-tutorial
python - Simple Regex tutorial | DaniWeb
November 15, 2009 - Nice intro. A couple of small but important tweaks for readers getting started. In regex, a dot matches any character, so writing .com also matches any-letter-then-com. Escape literal dots as \. and prefer raw strings (r"...") so backslashes are not eaten by Python.
🌐
Google
developers.google.com › google for education › python › python regular expressions
Python Regular Expressions | Python Education | Google for Developers
\d -- decimal digit [0-9] (some older regex utilities do not support \d, but they all support \w and \s) ^ = start, $ = end -- match the start or end of the string · \ -- inhibit the "specialness" of a character. So, for example, use \. to match a period or \\ to match a slash. If you are unsure if a character has special meaning, such as '@', you can try putting a slash in front of it, \@. If its not a valid escape sequence, like \c, your python ...
🌐
Programiz
programiz.com › python-programming › regex
Python RegEx (With Examples)
If you already know the basics of RegEx, jump to Python RegEx. To specify regular expressions, metacharacters are used. In the above example, ^ and $ are metacharacters.
Find elsewhere
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
Arguments read from a file must be one per line by default (but see also convert_arg_line_to_args()) and are treated as if they were in the same place as the original file referencing argument on the command line. So in the example above, the expression ['-f', 'foo', '@args.txt'] is considered equivalent to the expression ['-f', 'foo', '-f', 'bar'].
🌐
GeeksforGeeks
geeksforgeeks.org › python › regular-expression-python-examples
Python RegEx - GeeksforGeeks
August 14, 2025 - import re regex = r"([a-zA-Z]+) (\d+)" match = re.search(regex, "I was born on June 24") if match: print("Match at index %s, %s" % (match.start(), match.end())) print("Full match:", match.group(0)) print("Month:", match.group(1)) print("Day:", match.group(2)) else: print("The regex pattern does not match.") ... Metacharacters are special characters in regular expressions used to define search patterns. The re module in Python supports several metacharacters that help you perform powerful pattern matching. ... The backslash (\) makes sure that the character is not treated in a special way. This can be considered a way of escaping metacharacters. For example, if you want to search for the dot(.) in the string then you will find that dot(.) will be treated as a special character as is one of the metacharacters (as shown in the above table).
🌐
No Starch Press
nostarch.com › automate-boring-stuff-python-3rd-edition
Automate the Boring Stuff with Python, 3rd Edition | No Starch Press
July 11, 2023 - In this fully revised third edition of Automate the Boring Stuff with Python, you’ll learn how to use Python to write programs that do in minutes what would take you hours to do by hand—no prior programming experience required. Early chapters will teach you the fundamentals of Python through clear explanations and engaging examples.
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations
4 days ago - An enum.IntFlag class containing the regex options listed below. ... Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode (str) patterns, and is ignored for bytes patterns. Corresponds to the inline flag (?a). ... The U flag still exists for backward compatibility, but is redundant in Python 3 since matches are Unicode by default for str patterns, and Unicode matching isn’t allowed for bytes patterns.
🌐
Medium
medium.com › @tubelwj › commonly-used-python-regular-expression-examples-065526b5b8b5
Commonly Used Python Regular Expression Examples | by Gen. Devin DL. | Medium
January 2, 2025 - Here, we use “programmer” as the old content and “Python” as the new content, replacing “programmer” with “Python” in the string s. We can also use sub-expressions in regular expressions for more complex replacements, such as: import re # Define the old regex pattern for matching two words old_regex = r"(\w+) (\w+)" # Captures two words separated by a space # Define the new format for swapping the two captured words new_format = r"\2 \1" # Replaces the first word with the second and vice versa # Original string s = "Hello programmer" # Perform substitution using re.sub to swap the words s = re.sub(old_regex, new_format, s) # Print the result of the substitution print(s) # Output: programmer Hello
🌐
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 - The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object. But if a match is found in some other line, the Python RegEx Match function returns null. For example, consider the following code of Python re.match() function.
🌐
Medium
medium.com › pythons-gurus › mastering-regular-expressions-in-python-fa1020f7ea78
Regular Expressions in Python | Python’s Gurus
July 11, 2024 - Master Python regex with our guide. Learn pattern matching, special characters, and grouping techniques to enhance your text processing skills.
🌐
GitHub
github.com › BurntSushi › ripgrep
GitHub - BurntSushi/ripgrep: ripgrep recursively searches directories for a regex pattern while respecting your gitignore · GitHub
ripgrep recursively searches directories for a regex pattern while respecting your gitignore - BurntSushi/ripgrep
Author   BurntSushi
🌐
Real Python
realpython.com › regex-python
Regular Expressions: Regexes in Python (Part 1) – Real Python
October 21, 2023 - For example, rather than searching for a fixed substring like '123', suppose you wanted to determine whether a string contains any three consecutive decimal digit characters, as in the strings 'foo123bar', 'foo456bar', '234baz', and 'qux678'. Strict character comparisons won’t cut it here. This is where regexes in Python come to the rescue.
🌐
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 - In this guide, we explored the realm of Python RegEx or Regular Expressions. We started with common functions and fundamentals and go through more advanced concepts and practical examples. But remember doing real-life projects, that will count as an example for your career to deepen this ...
Top answer
1 of 6
160
import re
if re.match(regex, content):
  blah..

You could also use re.search depending on how you want it to match.

You can run this example:

"""
very nice interface to try regexes: https://regex101.com/
"""
# %%
"""Simple if statement with a regex"""
import re

regex = r"\s*Proof.\s*"
contents = ['Proof.\n', '\nProof.\n']
for content in contents:
    assert re.match(regex, content), f'Failed on {content=} with {regex=}'
    if re.match(regex, content):
        print(content)
2 of 6
59

if re.search(r'pattern', string):

Simple if-regex example:

if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

Complex if-regex example (pattern check, extract a substring, case insensitive):

search_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if search_object:
    assert "to" == search_object.group(1)     # what's between ought and be?

Notes:

  • Use re.search() not re.match. The match method restricts to the start of the string, a confusing convention. If you want that, search explicitly with caret: re.search(r'^...', ...) (Or in re.MULTILINE mode use \A)

  • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

  • In these examples, '\\b' or r'\b' is a special sequence meaning word-boundary for regex purposes. Not to be confused with '\b' or '\x08' backspace.

  • re.search() returns None if it doesn't find anything, which is always falsy.

  • re.search() returns a Match object if it finds anything, which is always truthy.

  • even though re.search() returns a Match object (type(search_object) is re.Match) I have taken to calling the return value a search_object. I keep returning to my own bloody answer here because I can't remember whether to use match or search. It's search, dammit.

  • a group is what matched inside pattern parentheses.

  • group numbering starts at 1.

  • Specs

  • Tutorial

🌐
Mimo
mimo.org › glossary › python › regex-regular-expressions
Python Regex: Master Regular Expressions in Python
In this example, re.search() checks if the word "learn" exists in the text and returns the first match. Regex is commonly used in Python 3 for working with unicode strings.
🌐
Semantic Versioning
semver.org
Semantic Versioning 2.0.0 | Semantic Versioning
Example: git tag v1.2.3 -m "Release version 1.2.3", in which case “v1.2.3” is a tag name and the semantic version is “1.2.3”. There are two. One with named groups for those systems that support them (PCRE [Perl Compatible Regular Expressions, i.e. Perl, PHP and R], Python and Go).
🌐
Django
docs.djangoproject.com › en › 6.0 › topics › db › models
Models | Django documentation | Django
The last method in this example is a property. The model instance reference has a complete list of methods automatically given to each model. You can override most of these – see overriding predefined model methods, below – but there are a couple that you’ll almost always want to define: ... A Python “magic method” that returns a string representation of any object.