Python re Module
Python's re The module is the standard library module for working with regular expressions.
A regular expression (regex or regexp) is a powerful tool for matching, searching and manipulating text.
Pass re With the module you can use regular expressions in Python to handle strings.
Why use the re module?
When processing text we often need to find specific patterns or replace certain characters, for example validating email addresses, extracting links from web pages, or formatting text. Writing code manually for these tasks can be very tedious, while regular expressions provide a concise and efficient way to solve them.
Basic usage of the re module
1. Import the re module
When using re Before using the module, you first need to import it:
import re
2. Common re module functions
2.1 re.match()
re.match() The function matches a regular expression from the beginning of a string. If it succeeds, it returns a match object; otherwise None。
Example
import
re
pattern
=
r
"hello"
text
=
"hello world"
match
=
re
.
match
(
pattern
,
text
)
if
match:
(
"Match succeeded:"
,
match.
group
(
)
)
else
:
(
"Match failed"
)
Output:
匹配成功: hello
2.2 re.search()
re.search() The function searches a string for the first match of a regular expression. Unlike re.match() in Vue 2,re.search() , it does not require the match to start at the beginning of the string.
Example
import
re
pattern
=
r
"world"
text
=
"hello world"
match
=
re
.
search
(
pattern
,
text
)
if
match:
(
"Match succeeded:"
,
match.
group
(
)
)
else
:
(
"Match failed"
)
Output:
匹配成功: world
2.3 re.findall()
re.findall() The function finds all substrings in a string that match a regular expression and returns them as a list.
Example
import
re
pattern
=
r
"\d+"
text
=
"There are 3 apples and 5 oranges."
matches
=
re
.
findall
(
pattern
,
text
)
(
"Numbers found:"
,
matches
)
Output:
找到的数字: ['3', '5']
2.4 re.sub()
re.sub() The function replaces the parts of a string that match a regular expression.
Example
import
re
pattern
=
r
"apple"
text
=
"I have an apple."
new_text
=
re
.
sub
(
pattern
,
"banana"
,
text
)
(
"Text after replacement:"
,
new_text
)
Output:
替换后的文本: I have an banana.
Basic regular expression syntax
1. Ordinary characters
Ordinary characters (such as letters and digits) match themselves directly.
Example
import
re
pattern
=
r
"cat"
text
=
"The cat is on the mat."
match
=
re
.
search
(
pattern
,
text
)
if
match:
(
"Match succeeded:"
,
match.
group
(
)
)
Output:
匹配成功: cat
2. Special characters
Some characters in regular expressions have special meanings. For example:
.: Matches any single character (except a newline).*: Matches the preceding character zero or more times.+: Matches the preceding character one or more times.?: Matches the preceding character zero or one time.\d: Matches any digit character (equivalent to[0-9])。\w: Matches any letter, digit or underscore character (equivalent to[a-zA-Z0-9_])。
Example
import
re
pattern
=
r
"\d+"
text
=
"The price is 100 dollars."
match
=
re
.
search
(
pattern
,
text
)
if
match:
(
"Match succeeded:"
,
match.
group
(
)
)
Output:
匹配成功: 100
3. Character sets
A character set matches any one of a group of characters. For example,[abc] Matches a、b or c。
Example
import
re
pattern
=
r
"[aeiou]"
text
=
"Hello World!"
matches
=
re
.
findall
(
pattern
,
text
)
(
"Vowels found:"
,
matches
)
Output:
找到的元音字母: ['e', 'o', 'o']
4. Groups
Groups let you combine several characters together and operate on them. For example,(abc) Matches abc。
Example
import
re
pattern
=
r
"(ab)+"
text
=
"ababab"
match
=
re
.
search
(
pattern
,
text
)
if
match:
(
"Match succeeded:"
,
match.
group
(
)
)
Output:
匹配成功: ababab
Practical Exercise
Exercise 1: validate an email address
Write a regular expression that validates the format of an email address.
Example
import
re
pattern
=
r
"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$"
=
"example@example.com"
if
re
.
match
(
pattern
,
)
:
(
"Valid email address"
)
else
:
(
"Invalid email address"
)
Exercise 2: extract phone numbers
Write a regular expression that extracts phone numbers from text.
Example
import
re
pattern
=
r
"\d{3}-\d{3}-\d{4}"
text
=
"My phone number is 123-456-7890."
match
=
re
.
search
(
pattern
,
text
)
if
match:
(
"Phone numbers found:"
,
match.
group
(
)
)
1. Core functions
| Method | Description | Example |
|---|---|---|
re.compile(pattern) |
Precompile regular expressions (improve reuse performance) | pat = re.compile(r'\d+') |
re.search(pattern, string) |
Search the string for the first match | re.search(r'\d+', 'a1b2') -> match '1' |
re.match(pattern, string) |
Match from the beginning of the string | re.match(r'\d+', '123a') -> match '123' |
re.fullmatch(pattern, string) |
Match the entire string completely | re.fullmatch(r'\d+', '123') -> match '123' |
re.findall(pattern, string) |
Return a list of all non-overlapping matches | re.findall(r'\d+', 'a1b22c') → ['1', '22'] |
re.finditer(pattern, string) |
Return an iterator of all matches (with position information) | for m in re.finditer(r'\d+', 'a1b2'): print(m.group()) |
re.sub(pattern, repl, string) |
Replace matches | re.sub(r'\d+', 'X', 'a1b2') → 'aXbX' |
re.split(pattern, string) |
Split the string by matches | re.split(r'\d+', 'a1b2c') → ['a', 'b', 'c'] |
re.escape() |
Escape special characters | re.escape("C:\\Users\\test.txt") |
re.purge() |
Clear the cache | re.purge() |
2. Match object (Match) methods / attributes
| Method/attribute | Description | Example |
|---|---|---|
group() |
Return the entire matched string | m.group() → 'abc' |
group(n) |
Return the contents of the nth capturing group | m = re.search(r'(\d)(\d)', '12'); m.group(1) → '1' |
groups() |
Return a tuple of all capturing groups | m.groups() → ('1', '2') |
start()/end() |
The start / end positions of the match | m.start() → 0 |
span() |
Return the span of the match (start, end) |
m.span() → (0, 2) |
3. Regular expression metacharacters (partial)
| Metacharacter | Description | Example match |
|---|---|---|
. |
Matches any character (except a newline) | a.c → 'abc' |
\d |
Matches a digit | \d+ → '123' |
\D |
Matches a non-digit | \D+ → 'abc' |
\w |
Matches a word character (letter, digit, underscore) | \w+ → 'Ab_1' |
\W |
Matches a non-word character | \W+ → '!@#' |
\s |
Matches a whitespace character (space, tab, etc.) | \s+ → ' \t' |
\S |
Matches a non-whitespace character | \S+ → 'abc' |
[] |
Character set | [A-Za-z] -> any letter |
^ |
Matches the beginning of the string | ^\d+ -> a digit at the beginning |
$ |
Matches the end of the string | \d+$ -> a digit at the end |
* |
Matches the preceding character 0 or more times | a* → '', 'aaa' |
+ |
Matches the preceding character 1 or more times | a+ → 'a', 'aaa' |
? |
Matches the preceding character 0 or 1 time | a? → '', 'a' |
{m,n} |
Matches the preceding character m to n times | a{2,3} → 'aa', 'aaa' |
\| |
OR operation | cat\|dog → 'cat' or 'dog' |
() |
Capture group | (\d+) -> extract digits |
4. Compilation flags (flags parameter)
| Flag | Description | Example |
|---|---|---|
re.IGNORECASE (re.I) |
Case-insensitive | re.search(r'abc', 'ABC', re.I) |
re.MULTILINE (re.M) |
Multiline mode (affects ^ and $) |
re.findall(r'^\d+', '1\n2', re.M) → ['1', '2'] |
re.DOTALL (re.S) |
Makes . match all characters including newlines |
re.search(r'a.*b', 'a\nb', re.S) |
re.ASCII |
Makes \w, \W etc. match ASCII characters only |
re.search(r'\w+', 'こん', re.ASCII) -> no match |
re.VERBOSE (re.X) |
Allows comments and whitespace inside regular expressions | re.compile(r'''\d+ # 匹配数字''', re.X) |
Example
- Extract email addresses
Example
import
re
text
=
"Contact: admin@example.com, support@test.org"
emails
=
re
.
findall
(
r
'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b'
,
text
)
(
emails
)
Output: ['admin@example.com', 'support@test.org']
- Replace the date format
Example
date_str
=
"Today is 05-15-2023"
new_str
=
re
.
sub
(
r
'(\d{2})-(\d{2})-(\d{4})'
,
r
'\3 Year \1 Month \2 Day'
,
date_str
)
(
new_str
)
Output: "Today is May 15, 2023"
- Multi-condition matching
Example
pattern
=
re
.
compile
(
r
'''
^(?P
:(?P
@(?P
$'''
,
re
.
VERBOSE
)
m
=
pattern.
match
(
"john:pass123@example.com"
)
if
m:
(
m.
groupdict
(
)
)
Output: {'username': 'john', 'password': 'pass123', 'domain': 'example.com'}
- Split a complex string
Example
text
=
"Apple1Banana2Cherry3Date"
parts
=
re
.
split
(
r
'\d+'
,
text
)
(
parts
)
Output: ['Apple', 'Banana', 'Cherry', 'Date']
Notes
-
Raw strings: It is recommended to use raw strings (
r'\d') for regular expressions to avoid escaping conflicts. -
Greedy matching: Greedy matching is the default (for example
.*matches the longest possible), use.*?for non-greedy matching. -
Performance optimization: Regular expressions used frequently should preferably be
re.compile()precompiled. -
Backtracking issues: Complex regular expressions can cause performance problems (such as nested quantifiers
(a+)+)。