如何在Python中使用正则表达式?
在Python中使用正则表达式主要通过内置的re
模块实现。正则表达式用于匹配、查找、替换字符串中的特定模式,是处理文本的强大工具。以下是使用正则表达式的核心方法和示例:
一、基本用法步骤
- 导入re模块:
import re
- 定义正则表达式模式:用字符串表示,特殊字符需转义(如
\d
表示数字) - 使用re模块函数:如
match()
、search()
、findall()
等处理文本
二、常用函数及示例
1. re.match(pattern, string)
- 从字符串开头匹配模式,成功返回匹配对象,否则返回
None
import re# 匹配以"Hello"开头的字符串
result = re.match(r"Hello", "Hello World")
if result:print("匹配成功:", result.group()) # 输出: 匹配成功: Hello
else:print("匹配失败")
2. re.search(pattern, string)
- 在整个字符串中查找第一个匹配项,不要求从开头开始
# 查找字符串中的数字
result = re.search(r"\d+", "年龄: 25, 身高: 180")
if result:print("找到数字:", result.group()) # 输出: 找到数字: 25
3. re.findall(pattern, string)
- 查找字符串中所有匹配的子串,返回列表
# 提取所有邮箱地址
text = "联系我们: a@example.com, b@test.org"
emails = re.findall(r"\w+@\w+\.\w+", text)
print(emails) # 输出: ['a@example.com', 'b@test.org']
4. re.sub(pattern, repl, string)
- 替换字符串中所有匹配的子串,返回替换后的新字符串
# 将所有数字替换为"*"
text = "密码: 123456, 验证码: 789"
new_text = re.sub(r"\d+", "*", text)
print(new_text) # 输出: 密码: *, 验证码: *
5. re.split(pattern, string)
- 根据匹配的模式分割字符串,返回列表
# 用逗号或空格分割字符串
text = "apple, banana orange; grape"
parts = re.split(r"[,; ]+", text) # 匹配逗号、分号或空格(可多个)
print(parts) # 输出: ['apple', 'banana', 'orange', 'grape']
三、常用正则表达式符号
符号 | 含义 | 示例 |
---|---|---|
. | 匹配任意字符(除换行) | a.b 匹配 “aab”、“acb” |
* | 前面元素出现0次或多次 | ab* 匹配 “a”、“ab”、“abb” |
+ | 前面元素出现1次或多次 | ab+ 匹配 “ab”、“abb” |
? | 前面元素出现0次或1次 | ab? 匹配 “a”、“ab” |
^ | 匹配字符串开头 | ^Hello 匹配以Hello开头 |
$ | 匹配字符串结尾 | world$ 匹配以world结尾 |
[] | 字符集,匹配其中任意一个字符 | [abc] 匹配 “a”、“b”、“c” |
\d | 匹配数字(等价于[0-9] ) | \d{3} 匹配3位数字 |
\w | 匹配字母、数字、下划线 | \w+ 匹配单词 |
() | 分组,提取匹配的子串 | (\d+)-(\d+) 匹配"123-456" |
四、进阶技巧:编译正则表达式
对于频繁使用的模式,可先用re.compile()
编译,提高效率:
# 编译模式
pattern = re.compile(r"\d{3}-\d{4}") # 匹配如"123-4567"的格式# 重复使用
text1 = "电话: 123-4567"
text2 = "传真: 890-1234"
print(pattern.search(text1).group()) # 123-4567
print(pattern.search(text2).group()) # 890-1234
五、实际案例:验证手机号
def is_valid_phone(phone):# 匹配中国大陆手机号(11位数字,以1开头)pattern = r"^1[3-9]\d{9}$"return bool(re.match(pattern, phone))print(is_valid_phone("13812345678")) # True
print(is_valid_phone("1234567890")) # False(长度不足)
通过re
模块,你可以灵活处理各种文本提取、验证和替换需求,熟练掌握后能极大提升文本处理效率。