Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

Python Regular Expressions: How to Use the `re` Module

A practical guide to Python’s re module, from safe pattern strings and matching choices to captures, flags, Unicode behavior, and reusable compiled patterns.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s re module to search, validate, extract, split, or replace text with patterns. The key choices are how much of the input must match—its beginning, any position, or the entire string—and whether your pattern should treat characters as Unicode or ASCII. In Python source, raw string notation such as r"d+" is usually the clearest way to write a regex.

Write regex patterns safely in Python

A regular expression has its own syntax, but Python also parses the string literal containing it. Since both layers use backslashes, an ordinary string may need doubled backslashes. For example, r"d+" passes d+ to the regex parser as written; with a regular string, you would need "\d+".

As an Amazon Associate I earn from qualifying purchases.

Raw strings avoid most of that double escaping, but they do not validate the regex itself: the pattern must still follow re syntax. Python warns that invalid escape sequences in ordinary string literals produce a SyntaxWarning and may become a SyntaxError. See the Python 3.14.8 re reference for pattern syntax and version-specific details.

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

Choose the operation that matches your task

The three most important matching functions differ by where they allow a match:

Operation Where it looks Typical use
re.match(pattern, text) Only at the beginning of the string Check a prefix or parse from the start
re.search(pattern, text) At any position; returns the first match Find a pattern somewhere in text
re.fullmatch(pattern, text) Requires the entire selected string region to match Validate that all input follows a format

For example, if a field must contain only digits, re.fullmatch(r"d+", value) expresses the whole-input requirement. A successful re.search() would establish only that some substring contains digits, not that the rest of the value is valid.

Each returns a match object when it finds a match and None otherwise. A match object can represent a zero-length match, so do not treat every successful result as proof that at least one character was consumed.

Anchors and multiline mode

re.MULTILINE changes how ^ and $ recognize line boundaries. It does not make re.match() check every line: that function remains restricted to the beginning of the string. Use search() or an iteration method when looking for matches later in a multiline string.

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

Extract, iterate, split, or replace matches

Collect matches with findall() or finditer()

re.findall() returns non-overlapping matches. Its result shape depends on capturing parentheses:

  • No capturing groups: a list of strings containing whole matches.
  • One capturing group: a list of strings containing that group.
  • Multiple capturing groups: a list of tuples, one tuple per match.

Use re.finditer() when you want an iterator of match objects instead; those objects provide access to the matched text and captured groups.

Split around matches

re.split() divides a string wherever the pattern matches. If the pattern contains capturing groups, the captured separators are included in the result. Account for that when writing code that expects alternating fields or a fixed list shape. In Python 3.13, passing maxsplit and flags positionally to re.split() was deprecated; check the reference for the version your project supports.

Replace matches with sub()

re.sub() replaces matching text. Replacement strings can refer to captured groups, making it possible to rearrange or preserve parts of a match. Use a raw string for the pattern, and check the replacement-string syntax separately from the pattern syntax.

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

Understand Unicode and ASCII character classes

For str patterns, Unicode matching is the default. Shorthand classes such as w, d, and s therefore follow Unicode behavior rather than being limited to ASCII characters.

Use re.ASCII (or re.A) when those shorthand classes should be ASCII-only. This changes several character classes, including w, d, and s. Choose deliberately when validating formats intended to accept only ASCII text.

re.LOCALE applies only to bytes patterns. The Python documentation discourages it in favor of Unicode behavior, so it is not the general solution for text matching.

Use flags to adjust matching behavior

  • re.IGNORECASE or re.I: match without regard to case; Unicode case behavior applies unless ASCII behavior is requested.
  • re.MULTILINE or re.M: let ^ and $ match line boundaries as documented.
  • re.DOTALL or re.S: let . match newline characters.
  • re.ASCII or re.A: narrow several shorthand classes for Unicode patterns to ASCII behavior.
  • re.VERBOSE or re.X: allow whitespace and comments in a pattern, with syntax exceptions such as character classes and escaped spaces.

Flags can be passed to module-level functions or used when compiling a pattern. Consult the Python Regular Expression HOWTO alongside the reference for additional explanation and examples.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 clearer

re.compile() creates a reusable pattern object with methods such as search(), match(), fullmatch(), findall(), finditer(), split(), and substitution methods. Compiled-pattern searches also support pos and endpos bounds.

For a pattern used repeatedly, compiling it can make reuse explicit and is documented as more efficient. For a short, one-off operation, module-level functions are often simpler. The HOWTO notes that Python caches recent patterns, so it is not necessary to compile every expression just because it appears in more than one call.

Check version-specific details

The documentation linked here is for Python 3.14.8. If your project supports other Python versions, consult that version’s reference before depending on newer APIs or deprecation behavior. For example, re.fullmatch() was added in Python 3.4, and re.NOFLAG was added in Python 3.11.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.