Python Regular Expressions (re module): Syntax, Functions, and Examples
This article introduces Python's regular expression capabilities via the re module, explaining core concepts, basic syntax, and key functions like match, search, and sub, accompanied by detailed code examples and illustrations of advanced regex constructs.
Regular expressions (regex) are logical formulas for matching patterns in strings, using special characters called metacharacters. In Python, the re module provides full regex functionality.
The module offers functions such as re.match() , re.search() , and re.sub() , each taking a pattern, a target string, and optional flags.
re.match() attempts to match the pattern only at the beginning of the string and returns a match object or None . Example:
re.match(pattern, string, flags=0) # Example
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() :', matchObj.group(1))
print('matchObj.group() :', matchObj.group(2))
print('matchObj.group() :', matchObj.group(3))
else:
print('no match!')re.search() scans the entire string and returns the first occurrence of the pattern. Example:
re.search(pattern, string, flags=0) # Example
import re
line = 'i can speak good english'
matchObj = re.search('(.*) (.*?) (.*)', line)
if matchObj:
print('matchObj.group() :', matchObj.group())
print('matchObj.group() :', matchObj.group(1))
print('matchObj.group() :', matchObj.group(2))
print('matchObj.group() :', matchObj.group(3))
else:
print('no match!')re.sub() replaces occurrences of the pattern with a replacement string. Syntax:
re.sub(pattern, repl, string, max=0) # Example
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)The tutorial also covers special regex constructs such as character classes, predefined character sets, quantifiers, non‑greedy matching, grouping with parentheses, back‑references, anchors, and other advanced syntaxes, illustrated with diagrams.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.