Skip to content

Regular 表达式

Match and extract 文本模式使用 re 模块: 搜索, match, 分组, and substitution.

你将学到

  • Use re.搜索, re.match, and re.findall
  • Capture 分组使用 parentheses
  • Apply quantifiers, anchors, and character 类
  • Substitute 文本使用 re.sub
  • 编译模式 for reuse and 性能

概念讲解

The re Module

Python's re module provides regular expression support. A regex is a pattern that describes a set of strings — useful for validation, extraction, and substitution:

import re

# Search for a pattern in a string
match = re.search(r"\d{3}", "Call 555-1234 for help")
if match:
    print(match.group())  # 555
    print(match.start())  # 5 (position where match starts)

Always use raw strings (r"...) for regex 模式 — 不使用 r` prefix, Python interprets backslash escapes before the regex engine sees them, causing subtle bugs.

re.search vs re.match vs re.fullmatch

  • 2 — find the pattern anywhere in the string
  • 3 — match only at the beginning of the string
  • 4 — the entire string must match
import re

text = "Hello, 世界!"

print(re.search(r"世界", text))   # <Match object> — found
print(re.match(r"Hello", text))    # <Match object> — matches at start
print(re.match(r"世界", text))    # None — not at the start
print(re.fullmatch(r"Hello, 世界!", text))  # <Match object> — entire string

All three return a Match object on success or 无 on failure. Always check for 无 before calling .分组().

Character Classes and Quantifiers

import re

# Character classes
re.findall(r"[aeiou]", "Hello 世界")     # ['e', 'o', 'o'] — vowels
re.findall(r"[0-9]+", "abc123def456")     # ['123', '456'] — digit sequences
re.findall(r"[-Z][-z]+", "Hello 世界") # ['Hello', 'World'] — capitalized words

# Predefined classes
# \d — digits       \D — non-digits
# \w — word chars   \W — non-word chars
# \s — whitespace   \S — non-whitespace
# .  — any char except newline

# Quantifiers
# * — zero or more    + — one or more
# ? — zero or one     {n} — exactly n
# {n,m} — between n and m
re.findall(r"\d+", "a1b22c333")          # ['1', '22', '333']
re.findall(r"\w{4}", "cat dog bird fish") # ['bird', 'fish'] — exactly 4 word chars

Capture Groups

Parentheses () create capture groups that extract specific parts of the match:

import re

# Extract area code and number from a phone number
pattern = r"(\d{3})-(\d{3})-(\d{4})"
match = re.search(pattern, "Call 555-123-4567")

if match:
    print(match.group(0))  # 555-123-4567 (entire match)
    print(match.group(1))  # 555 (first group)
    print(match.group(2))  # 123 (second group)
    print(match.group(3))  # 4567 (third group)
    print(match.groups())  # ('555', '123', '4567')

# Named groups
pattern = r"(?P<区域>\d{3})-(?P<数字>\d{3}-\d{4})"
match = re.search(pattern, "555-123-4567")
print(match.group("区域"))    # 555
print(match.group("数字"))  # 123-4567

Named groups ((?P<name>...)) make complex patterns much more readable — you access parts by name instead of index.

re.findall and re.finditer

import re

# findall — return all matches as a list
emails = re.findall(r"[\w.]+@[\w.]+", "Contact [email protected] or [email protected]")
print(emails)  # ['[email protected]', '[email protected]']

# With groups, findall returns tuples
pairs = re.findall(r"(\w+)=(\d+)", "x=1, y=2, z=3")
print(pairs)  # [('x', '1'), ('y', '2'), ('z', '3')]

# finditer — return match objects (for position info)
for m in re.finditer(r"\d+", "a1b22c333"):
    print(f"找到 {m.分组()} at 位置 {m.开始()}")

re.sub — Substitution

import re

# Replace all occurrences
result = re.sub(r"\d+", "#", "abc123def456")
print(result)  # abc#def#

# Replace with a function
def double_match(match):
    return str(int(match.group()) * 2)

result = re.sub(r"\d+", double_match, "abc123def456")
print(result)  # abc246def912

# Limit number of replacements
result = re.sub(r"\d", "X", "a1b2c3d4", count=2)
print(result)  # aXbXc3d4

The function form of re.sub is powerful — it lets you transform each match dynamically.

Anchors

import re

# ^ — start of string    $ — end of string
# \b — word boundary

re.findall(r"^Hello", "Hello 世界")   # ['Hello'] — at start
re.findall(r"世界$", "Hello 世界")   # ['World'] — at end
re.findall(r"\bcat\b", "cat catalog catch")  # ['cat'] — whole word only

Compiling Patterns

For patterns used repeatedly, compile them once for better performance:

import re

# Compile once, use many times
email_pattern = re.compile(r"^[\w.]+@[\w.]+\.\w+$")

# Now use the compiled pattern
print(email_pattern.match("ada@示例.com"))  # Match
print(email_pattern.match("not-an-email"))     # None

# Compiled patterns have all the same methods
emails = email_pattern.findall("[email protected] [email protected]")

Compiling is faster when you use the same pattern in a loop or many times — the regex engine does not need to re-parse the pattern each time.

Flags

import re

# re.IGNORECASE — case-insensitive
re.findall(r"hello", "Hello HELLO hello", re.IGNORECASE)  # ['Hello', 'HELLO', 'hello']

# re.MULTILINE — ^ and $ match at line boundaries
re.findall(r"^\w+", "line1\nline2\nline3", re.MULTILINE)  # ['line1', 'line2', 'line3']

# re.DOTALL — . matches newlines too
re.findall(r".+", "line1\nline2", re.DOTALL)  # ['line1\nline2']

Combine flags with |: re.IGNORECASE | re.MULTILINE.

示例代码

              import re

# Basic search
match = re.search(r"\d{3}-\d{4}", "Call 555-1234 for help")
if match:
    print(f"Found phone: {match.group()} at position {match.start()}")

# Character classes and quantifiers
vowels = re.findall(r"[aeiou]", "Hello World")
print(f"Vowels: {vowels}")

numbers = re.findall(r"\d+", "abc123def456ghi789")
print(f"Numbers: {numbers}")

# Capture groups — extract parts
phone_pattern = r"(\d{3})-(\d{3})-(\d{4})"
match = re.search(phone_pattern, "Phone: 555-123-4567")
if match:
    area, exchange, number = match.groups()
    print(f"Area: {area}, Exchange: {exchange}, Number: {number}")

# Named groups
date_pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
match = re.search(date_pattern, "Date: 2024-01-15")
if match:
    print(f"Year: {match.group('year')}, Month: {match.group('month')}")

# Email extraction
text = "Contact [email protected] or [email protected] for info"
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(f"Emails: {emails}")

# Substitution
redacted = re.sub(r"\d{4}", "****", "Card: 1234-5678-9012-3456")
print(f"Redacted: {redacted}")

# Substitution with a function
def censor(match):
    word = match.group()
    return word[0] + "*" * (len(word) - 1)

censored = re.sub(r"\b\w{4}\b", censor, "some bad word here")
print(f"Censored: {censored}")

# Compiled pattern for reuse
email_re = re.compile(r"^[\w.]+@[\w.]+\.\w+$")
test_emails = ["[email protected]", "invalid", "[email protected]"]
for email in test_emails:
    valid = bool(email_re.match(email))
    print(f"  {email}: {'valid' if valid else 'invalid'}")

# Flags
case_insensitive = re.findall(r"python", "Python PYTHON python", re.IGNORECASE)
print(f"Case-insensitive matches: {case_insensitive}")
            

Shows re.搜索, character 类, capture 分组 (numbered and named), email extraction, substitution (简单 and 使用函数), compiled 模式 for validation, and IGNORECASE flag.

动手试一试

  • Regex Tester

    测试 regex 模式 live — Python's re 模块 uses 相同语法.

  • 文本计数器

    Regex 是 perfect for counting 特定模式 in 文本.

常见错误

错误写法

不 using raw 字符串 (r'...') for regex 模式, causing backslash escape issues

正确做法

总是 prefix regex 模式使用 r: re.搜索(r'\d+', 文本). 不使用 r, Python interprets \d as escape 序列之前 regex engine sees 它. Raw 字符串通过 backslashes literally 到 regex engine.

错误写法

Calling .分组() on match result 不使用检查如果它 是无 首先

正确做法

re.搜索 and re.match 返回无 如果否 match 是找到. Calling .分组() on 无 raises AttributeError. 总是检查: 'match = re.搜索(...); 如果 match: print(match.分组())'. Or use re.findall 哪个总是返回列表.

相关速查表

练习 Regular 表达式

1 个练习

练习 Regular 表达式

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误