Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Master Python Regular Expressions: re.match(), re.search(), re.findall() – Practical Examples

What Is a Regular Expression in Python?

A regular expression (regex) is a compact textual description that tells Python how to locate patterns within a string. Regexes are indispensable for data extraction, validation, and transformation across codebases, logs, configuration files, and web scraping projects.

In Python, the re module ships with the interpreter and exposes a rich API for compiling patterns, searching, and replacing text. Whether you’re filtering user input, parsing logs, or scraping content from websites, a solid grasp of regex fundamentals saves time and reduces bugs.

Core Regex Concepts

Common Identifier Table

IdentifierDescriptionWhitespaceSpecial Escape
\dAny digit (0‑9)\n., +, *, ?, [], $, ^, (, ), {}, |, \
\DNon‑digit\s
\sSpace, tab, newline, etc.\t
\SNon‑space\e
\wAlphanumeric plus underscore\r
\WNon‑alphanumeric (excluding underscore)\f
.Any character except newline
\bWord boundary
\.Literal period
\{x}Exactly x occurrences

Getting Started with re

import re

The re module is part of Python’s standard library and requires no external dependencies. Common use‑cases include:

Example 1: \w+ and ^

Using these, we can capture the first word of a string:

import re
sample = "guru99, education is fun"
result = re.findall(r"^\w+", sample)
print(result)  # Output: ['guru99']

Removing the + would return only the first character: ["g"].

Example 2: Splitting on Whitespace with \s

The re.split() function can divide a string wherever a pattern matches. Using \s splits on any whitespace character.

import re
text = "we are splitting the words"
print(re.split(r"\s", text))  # ['we', 'are', 'splitting', 'the', 'words']

If the backslash is omitted, s is treated as a literal, resulting in splits at every s character.

Regex Methods Overview

Using re.match()

import re
text = "guru99 is a great platform"
match = re.match(r"^\w+", text)
print(match.group() if match else "No match")  # Output: guru99

Using re.search()

import re
text = "Software Testing is fun"
for pattern in ["Software testing", "guru99"]:
    found = re.search(pattern, text, re.IGNORECASE)
    print(f"Looking for '{pattern}' in '{text}' - {'found a match!' if found else 'no match'}")

Using re.findall()

import re
emails = "guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com"
found = re.findall(r"[\w\.-]+@[\w\.-]+", emails)
for e in found:
    print(e)

Regex Flags

Flags modify pattern behavior. Common flags include:

FlagDescription
re.M (re.MULTILINE)Make ^ and $ match the start and end of each line.
re.I (re.IGNORECASE)Ignore case distinctions.
re.S (re.DOTALL)Make dot match newlines.
re.U (re.UNICODE)Apply Unicode-aware character classes.
re.L (re.LOCALE)Make classes depend on the current locale.
re.X (re.VERBOSE)Allow whitespace and comments in the pattern.

Multiline Example

import re
text = """guru99
careerguru99	selenium"""
print(re.findall(r"^\w", text))          # ['g']
print(re.findall(r"^\w", text, re.MULTILINE))  # ['g', 'c', 's']

Python 2 Compatibility

All examples above are written for Python 3. If you must run them under Python 2, replace print() statements with the Python 2 syntax and ensure that the re module is imported in the same way.

Takeaway

Mastering Python regex gives you a powerful toolkit for text processing:

Python

  1. Python Regular Expressions (re Module) – A Practical Guide
  2. Python OOP Fundamentals: Classes, Objects, Inheritance, and Constructors Explained
  3. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
  4. Python Counter in collections – Efficient Counting, Updating, and Arithmetic Operations
  5. Creating ZIP Archives in Python: From Full Directory to Custom File Selection
  6. Master Python Unit Testing with PyUnit: A Practical Guide & Example
  7. Python List index() – How to Find Element Positions with Practical Examples
  8. Python Calendar Module: Expert Guide with Code Examples
  9. Master Python Multithreading: GIL Explained with Practical Examples
  10. Master Python Attrs: Build Advanced Data Classes with Practical Examples