python re模块常用方法
正则表达式基础语法
正则表达式(Regular Expression)是用于匹配字符串模式的工具,Python通过re
模块提供支持。以下为常见语法:
.
:匹配任意字符(除换行符)\d
:匹配数字(等价于[0-9]
)\w
:匹配字母、数字或下划线(等价于[a-zA-Z0-9_]
)\s
:匹配空白字符(空格、制表符等)[]
:匹配括号内的任意一个字符(如[aeiou]
匹配元音字母)^
:匹配字符串开头(或在[]
内表示取反)$
:匹配字符串结尾*
:匹配前一个字符0次或多次+
:匹配前一个字符1次或多次?
:匹配前一个字符0次或1次{n}
:匹配前一个字符恰好n次|
:或操作(如a|b
匹配a或b)
Python re模块常用方法
Python的re
模块提供以下核心函数:
re.match(pattern, string)
:从字符串开头匹配模式,返回Match
对象或None
。re.search(pattern, string)
:扫描整个字符串寻找匹配,返回第一个匹配的Match
对象。re.findall(pattern, string)
:返回所有非重叠匹配的列表。re.sub(pattern, repl, string)
:将匹配的模式替换为指定字符串。re.compile(pattern)
:预编译正则表达式,提升重复使用效率。
import re
text = "Python 3.10 released on 2021-10-04"
# 提取日期
date_match = re.search(r'\d{4}-\d{2}-\d{2}', text)
print(date_match.group()) # 输出: 2021-10-04
分组与捕获
使用括号()
创建捕获组,可通过group()
方法获取:
pattern = r'(\w+) (\d+)'
match = re.search(pattern, "Python 3")
print(match.group(1)) # 输出: Python
print(match.group(2)) # 输出: 3
mo
命名分组使用(?P<name>...)
语法:
pattern = r'(?P<lang>\w+) (?P<ver>\d+)'
match = re.search(pattern, "Python 3")
print(match.group('lang')) # 输出: Python
贪婪与非贪婪匹配
默认情况下,量词(*
, +
, ?
, {}
)是贪婪的,会尽可能匹配更多字符。添加?
转换为非贪婪模式:
# 贪婪匹配
greedy = re.search(r'<.*>', '<div>text</div>')
print(greedy.group()) # 输出: <div>text</div># 非贪婪匹配
non_greedy = re.search(r'<.*?>', '<div>text</div>')
print(non_greedy.group()) # 输出: <div>
常用正则表达式示例
邮箱验证:
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' re.match(pattern, "user@example.com")
URL提取:
pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' re.findall(pattern, "Visit https://www.example.com")
电话号码匹配(简单版):
pattern = r'\d{3}-\d{3}-\d{4}' re.search(pattern, "Call 123-456-7890")
性能优化建议
预编译正则:频繁使用的模式应通过
re.compile()
预编译。compiled_pattern = re.compile(r'\d+') compiled_pattern.findall("123 abc 456")
避免回溯灾难:复杂模式可能导致性能问题,尽量使用具体匹配范围。
使用原始字符串:在模式字符串前加
r
(如r'\d'
)避免转义字符混淆。