Python 常用的正则表达式

发布于:2025-08-17 ⋅ 阅读:(13) ⋅ 点赞:(0)

正则表达式(Regular Expression)是一种强大的文本处理工具,它使用特定的模式来描述、匹配一系列符合某个语法规则的字符串。在Python中,通过re模块提供正则表达式功能。

正则表达式的作用

  1. 文本匹配:检查字符串是否符合特定模式
  2. 文本查找:在字符串中查找符合模式的子串
  3. 文本替换:将符合模式的子串替换为其他内容
  4. 文本分割:按照模式将字符串分割成多个部分

re模块常用方法


1. re.match(pattern, string) - 从字符串开头匹配模式

示例

import re

result = re.match(r'hello', 'hello world')
print(result.group())  # 输出: hello

result = re.match(r'world', 'hello world')
print(result)  # 输出: None

说明

  • 第一个例子匹配成功,因为字符串以"hello"开头
  • 第二个例子返回None,因为字符串不是以"world"开头
  • match()只检查字符串开头,相当于在模式前加了^

2. re.search(pattern, string) - 在字符串中搜索第一个匹配项

示例

import re

result = re.search(r'\d+', 'Order 12345 placed on 2023-04-15')
print(result.group())  # 输出: 12345

result = re.search(r'apple', 'I like oranges')
print(result)  # 输出: None

说明

  • 第一个例子找到字符串中第一个连续数字"12345"
  • 第二个例子返回None,因为字符串中没有"apple"
  • match()不同,search()会扫描整个字符串

3. re.findall(pattern, string) - 返回所有匹配项的列表

示例

import re

results = re.findall(r'\d+', 'Order 12345 placed on 2023-04-15')
print(results)  # 输出: ['12345', '2023', '04', '15']

results = re.findall(r'[A-Z][a-z]+', 'John Doe and Jane Smith')
print(results)  # 输出: ['John', 'Doe', 'Jane', 'Smith']

说明

  • 第一个例子找到所有连续数字序列
  • 第二个例子找到所有首字母大写的单词
  • 返回的是字符串列表,没有匹配对象信息

4. re.finditer(pattern, string) - 返回匹配项的迭代器

示例

import re

matches = re.finditer(r'\d{2}', 'Order 12345 placed on 2023-04-15')
for match in matches:
    print(f"找到