正则表达式最常用 10 个写法

正则表达式是处理字符串的强大工具,本文整理 Python 中最常用的 10 种写法。

1. 导入与基础匹配

import re

# 查找匹配
text = "我的邮箱是 test@example.com"
pattern = r'\w+@\w+\.\w+'
result = re.search(pattern, text)
print(result.group())  # test@example.com

# 查找所有
text = "我有三个邮箱: a@test.com, b@test.com, c@test.com"
emails = re.findall(r'\w+@\w+\.\w+', text)
print(emails)  # ['a@test.com', 'b@test.com', 'c@test.com']

2. 字符类 [abc]

# 匹配字符集合
re.search(r'[aeiou]', "hello")   # 匹配 e
re.search(r'[0-9]', "a1b2")    # 匹配 1
re.search(r'[a-zA-Z]', "Hello")  # 匹配 H

# 否定字符类
re.search(r'[^0-9]', "123a")  # 匹配 a

3. 量词 * + ?

text = "aabbbbcccc"

re.search(r'a*', text)   # a* 零个或多个 → aa
re.search(r'a+', text)   # a+ 一个或多个 → aa
re.search(r'b?', text)   # b? 零个或一个 → b (优先一个)

# 精确数量
re.search(r'c{3}', text)  # c{3} 精确3个 → ccc
re.search(r'c{2,4}', text)  # c{2,4} 2到4个 → cccc

4. 边界匹配 ^ $

# 行首匹配
re.search(r'^hello', 'hello world')  # 匹配
re.search(r'^world', 'hello world')  # 不匹配 None

# 行尾匹配
re.search(r'world$', 'hello world')  # 匹配
re.search(r'hello$', 'hello world')  # 不匹配 None

# 整个字符串匹配
re.fullmatch(r'hello', 'hello')  # 匹配
re.fullmatch(r'hello', 'hello world')  # 不匹配

5. 元字符 . \d \w \s

# . 任意字符(换行符除外)
re.search(r'a.c', 'abc')  # abc

# \d 数字 [0-9]
re.search(r'\d{3}', 'a123b')  # 123

# \w 单词字符 [a-zA-Z0-9_]
re.search(r'\w+', 'hello_world')  # hello_world

# \s 空白字符
re.search(r'a\sb', 'a b')  # a b

# 反义
\D  # 非数字
\W  # 非单词字符
\S  # 非空白字符

6. 分组 ()

text = "2024-04-12"

# 分组提取
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text)
print(match.group(0))  # 2024-04-12 整个匹配
print(match.group(1))  # 2024 年
print(match.group(2))  # 04 月
print(match.group(3))  # 12 日

# 命名分组
match = re.search(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', text)
print(match.group('year'))  # 2024

7. 或运算 |

re.search(r'cat|dog', 'I like cat')   # cat
re.search(r'cat|dog', 'I like dog')   # dog

# 优先级
re.search(r'(foo|foot)', 'football')  # foo

8. 替换 re.sub

text = "hello world"

# 简单替换
re.sub(r'world', 'python', text)  # hello python

# 使用分组
re.sub(r'(\w+) (\w+)', r'\2 \1', text)  # world hello

# 替换函数
def to_upper(match):
    return match.group(0).upper()

re.sub(r'hello', to_upper, text)  # HELLO world

9. 编译与旗帜

# 编译复用
pattern = re.compile(r'\d+')
pattern.findall('a1b2c3')  # ['1', '2', '3']

# 常用旗帜
re.IGNORECASE  # 忽略大小写
re.MULTILINE   # ^ $ 匹配每行
re.DOTALL     # . 匹配换行

re.search(r'hello', 'HELLO', re.IGNORECASE)  # 匹配

10. 实用示例

提取手机号

text = "我的电话: 13812345678, 另一个: 13900000000"
phones = re.findall(r'1[3-9]\d{9}', text)
# ['13812345678', '13900000000']

提取中文

text = "Hello 你好 World 世界"
chinese = re.findall(r'[\u4e00-\u9fff]+', text)
# ['你好', '世界']

密码验证

def validate_password(password):
    if len(password) < 8:
        return False
    if not re.search(r'[A-Za-z]', password):
        return False
    if not re.search(r'\d', password):
        return False
    return True

HTML 标签清理

html = '<p>Hello <b>World</b></p>'
clean = re.sub(r'<[^>]+>', '', html)
# Hello World

快速对照表

写法 说明
[abc] 匹配 a, b, 或 c
[^abc] 不匹配 a, b, c
\d 数字
\w 单词字符
^abc abc 开头
abc$ abc 结尾
a* 零个或多个 a
a+ 一个或多个 a
a{3} 精确 3 个 a
(abc) 分组

正则表达式是文本处理的瑞士军刀,掌握这些常用写法能解决大部分字符串处理问题。