Python正则表达式使用主要通过re
模块实现,其核心功能包括模式匹配、文本提取、替换及拆分。以下是关键要点:
一、基础语法与元字符
-
导入模块
使用
import re
导入正则表达式模块。 -
元字符应用
-
.
:匹配任意字符(除换行符) -
^
:匹配字符串开头 -
$
:匹配字符串结尾 -
*
:匹配0次或多次 -
+
:匹配1次或多次 -
?
:匹配0次或1次 -
\d
:匹配数字 -
\w
:匹配字母、数字或下划线 -
\s
:匹配空白字符
-
二、核心函数与操作
-
匹配函数
-
re.match()
:从字符串开头匹配模式 -
re.search()
:搜索第一个匹配位置
-
-
查找与替换
-
re.findall()
:返回所有匹配子串列表 -
re.sub()
:替换匹配模式
-
-
拆分功能
re.split()
:根据模式拆分字符串
三、实际应用案例
-
邮箱提取
text = "support@example.com 或 sales.department@another-example.net.cn" pattern = r'\w+@\w+\.\w+' emails = re.findall(pattern, text) print(emails) # 输出: ['support@example.com', 'sales.department@another-example.net.cn']
-
电话号码匹配
text = "我的电话是123456,他的电话是789000" pattern = r'\d+' numbers = re.findall(pattern, text) print(numbers) # 输出: ['123456', '789000']
-
拆分复杂字符串
text = "apple,banana;orange|grape" pattern = r'[,;|]' fruits = re.split(pattern, text) print(fruits) # 输出: ['apple', 'banana', 'orange', 'grape']
四、注意事项
-
使用原始字符串(前缀
r
)避免转义字符问题; -
复杂模式可能影响性能,需优化。