Fundamentals 8 min read

Python Regular Expressions with the re Module: Syntax, Functions, and Practical Examples

This article introduces regular expressions, explains Python's re module and its core functions such as match, search, and sub, and demonstrates their usage with clear code examples and visual illustrations of special syntax, character classes, and grouping constructs.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Regular Expressions with the re Module: Syntax, Functions, and Practical Examples

Regular expressions are logical formulas for processing strings, using predefined special characters (metacharacters) and their combinations to define pattern strings that filter or match text. They are widely used in web crawling, data analysis, and string validation.

In Python, the re module provides full regex capabilities, offering both function-based and method-based interfaces that accept a pattern string as the first argument.

2 Basic Syntax

2.1 match function

The re.match(pattern, string, flags=0) function attempts to match the pattern only at the beginning of the string.

<code>re.match(pattern, string, flags = 0)</code>

Parameters:

pattern – the regular expression to match.

string – the target string to be searched.

flags – optional bitwise OR of flag constants that modify the matching behavior.

It returns a match object on success or None on failure; the match object’s group() or groups() methods retrieve the captured substrings.

Example (no match from the start):

<code>#未从初始位置匹配,会返回None
import re
line = 'i can speak good english'
matchObj = re.match(r'\s(\w*)\s(\w*).*', line)
if matchObj:
    print('matchObj.group() :', matchObj.group())
    print('matchObj.group(1) :', matchObj.group(1))
    print('matchObj.group(2) :', matchObj.group(2))
    print('matchObj.group(3) :', matchObj.group(3))
else:
    print('no match!')</code>

Example (match from the start):

<code>import re
line = 'i can speak good english'
matchObj = re.match(r'(i)\s(\w*)\s(\w*).*', line)
if matchObj:
    print('matchObj.group() :', matchObj.group())
    print('matchObj.group(1) :', matchObj.group(1))
    print('matchObj.group(2) :', matchObj.group(2))
    print('matchObj.group(3) :', matchObj.group(3))
else:
    print('no match!')</code>

2.2 search function

The re.search(pattern, string, flags=0) function scans the entire string and returns the first match found at any position.

<code>re.search(pattern, string, flags = 0)</code>

Parameters are the same as for match . It also returns a match object or None .

Example:

<code>import re
line = 'i can speak good english'
matchObj = re.search('(.*) (.*?) (.*)', line)
if matchObj:
    print('matchObj.group() :', matchObj.group())
    print('matchObj.group(1) :', matchObj.group(1))
    print('matchObj.group(2) :', matchObj.group(2))
    print('matchObj.group(3) :', matchObj.group(3))
else:
    print('no match!')</code>

2.3 sub function

The re.sub(pattern, repl, string, max=0) method replaces all occurrences of the pattern with repl (or up to max times) and returns the modified string.

<code>re.sub(pattern, repl, string, max=0)</code>

Example:

<code>import re
line = 'i can speak good english'
speak = re.sub(r'can','not', line)
print(speak)
speak1 = re.sub(r'\s','', line)  # remove all spaces
print(speak1)</code>

3 Special Regex Syntax

3.1 Character Classes

3.2 Special Character Classes

3.3 Repetition

3.4 Non‑greedy Repetition

3.5 Grouping with Parentheses

3.6 Backreferences

3.7 Anchors

3.8 Bracketed Special Syntax

For further reading, see the recommended articles on Python performance tips, decorators, data‑analysis tricks, and user‑profile implementation.

Pythonregular expressionsregexcoding tutorialre module
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.