Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use Python’s re module by first deciding where a match is allowed: match() checks at the start, search() finds a match anywhere, and fullmatch() requires the entire selected text to match. Write most patterns as raw strings such as r"d+" so Python’s string parser does not consume the backslashes intended for the regex engine.

Write a pattern safely in Python

A regular expression and a Python string literal both use backslashes. In an ordinary quoted string, a backslash may be interpreted by Python before the regex engine sees the pattern. Raw string notation passes the backslash through, which is why patterns are commonly written with an r prefix:

import re

pattern = r"d+"
match = re.search(pattern, "Order 248")
if match:
    print(match.group())  # 248

Raw strings do not make invalid regex syntax valid; the pattern must still follow the regex language. Python warns that invalid escape sequences in ordinary string literals can produce a SyntaxWarning and may become a SyntaxError. See the Python 3.14.8 re reference for the current documented behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the operation by match location

Operation What it requires Typical use
re.match(pattern, text) A match at the beginning of the string Checking a prefix or parsing text that must begin with a particular form
re.search(pattern, text) A match at any position; returns the first one found Finding a substring embedded in text
re.fullmatch(pattern, text) The entire selected string region must match Validating that all input conforms to a pattern

For example, given "ref-42-end", re.search(r"d+", text) finds 42, while re.fullmatch(r"d+", text) fails because the whole string is not digits. Use fullmatch() for whole-input validation; a successful search() proves only that some substring matched.

re.match() remains anchored at the start of the string even when multiline mode is enabled. The MULTILINE flag changes how ^ and $ recognize line boundaries; it does not turn match() into a search at the start of every line. A successful operation returns a match object, while no match returns None. A zero-length match is still a successful match, not None.

Pick the right operation for extracting or changing text

Find all matches or iterate over match objects

findall() returns non-overlapping matches. Its result depends on capturing groups: with no capturing groups it returns strings for whole matches; with one group it returns that group’s strings; with multiple groups it returns tuples. Use finditer() when you need match objects, for example to access match positions or groups as you process results.

Split text and keep delimiters when needed

split() separates text at pattern matches. If the pattern has capturing groups, the captured separators are included in the result. That can be useful when the delimiter itself must be retained, but it changes the output list and should be accounted for by later code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Replace matches

sub() replaces occurrences matching the pattern. Replacement strings can refer to captured groups, letting you rearrange or preserve parts of each match. Use capturing parentheses only where extraction or replacement needs them; captures also affect findall() and split().

Use flags to control matching behavior

  • re.IGNORECASE (or re.I) ignores case differences. For Unicode string patterns, case-insensitive behavior follows Unicode unless ASCII behavior is requested.
  • re.MULTILINE (or re.M) changes the line-boundary behavior of ^ and $; it does not change the anchoring behavior of match().
  • re.DOTALL (or re.S) lets . match newline characters.
  • re.ASCII (or re.A) narrows shorthand classes such as w, d, and s to ASCII behavior for Unicode patterns.
  • re.VERBOSE (or re.X) allows whitespace and comments in a pattern to make it easier to read. Whitespace handling has exceptions, including inside character classes and for escaped spaces.
  • re.LOCALE (or re.L) applies only to bytes patterns. Python’s documentation discourages it in favor of Unicode matching.

Understand Unicode, ASCII, and bytes

For patterns and text represented as Python str, Unicode matching is the default. As a result, shorthand character classes may match more than ASCII characters. If a format specifically requires ASCII-only behavior, use re.ASCII and confirm that its effects on shorthand classes fit the requirement. The LOCALE flag is restricted to bytes patterns and is discouraged; do not assume it is a general way to change Unicode string matching.

Choose a consistent text type for the pattern and input: use string patterns with str text, or bytes patterns with byte data. The official Regular Expression HOWTO explains the module’s behavior and the practical distinctions among these choices.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Compile patterns when reuse makes it useful

re.compile() creates a reusable pattern object with methods including match(), search(), fullmatch(), findall(), finditer(), split(), and substitution methods. Compiled-pattern searches also accept pos and endpos bounds, which let a search operate within a region of the input.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import re

number = re.compile(r"d+")
for match in number.finditer("A12 B345"):
    print(match.group(), match.span())

Compilation is useful when the same expression is reused and can make the code’s intent clearer. For a short, one-off operation, module-level functions are convenient. The HOWTO notes that Python caches recently used patterns, so compiling every expression is not a requirement for performance.

Check version-sensitive details

The Python 3.14.8 reference documents the current API. fullmatch() was added in Python 3.4, and re.NOFLAG was added in Python 3.11. Positional use of maxsplit and flags in re.split() has been deprecated since Python 3.13. If a project supports older Python versions or depends on a deprecated call style, check the documentation for the version it actually runs: https://docs.python.org/3/library/re.html.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.