Python正则分组案例如何提取内容

wen python案例 30

本文目录导读:

Python正则分组案例如何提取内容

  1. 基础分组提取
  2. 命名分组提取
  3. 多个匹配提取
  4. 使用 finditer() 迭代匹配
  5. 复杂嵌套分组
  6. 非捕获分组
  7. 实战:提取URL参数
  8. 分组提取的常用方法
  9. 注意事项

我来详细介绍Python正则分组提取内容的几种常见案例。

基础分组提取

使用 创建分组

import re
# 提取日期中的年、月、日
text = "2024-01-15"
pattern = r'(\d{4})-(\d{2})-(\d{2})'
match = re.search(pattern, text)
if match:
    year = match.group(1)
    month = match.group(2)
    day = match.group(3)
    print(f"年: {year}, 月: {month}, 日: {day}")
    # 输出: 年: 2024, 月: 01, 日: 15

命名分组提取

使用 (?P<name>...) 语法

import re
# 提取邮箱的用户名和域名
email = "user123@example.com"
pattern = r'(?P<username>\w+)@(?P<domain>\w+\.\w+)'
match = re.search(pattern, email)
if match:
    username = match.group('username')
    domain = match.group('domain')
    print(f"用户名: {username}, 域名: {domain}")
    # 输出: 用户名: user123, 域名: example.com

多个匹配提取

使用 findall()

import re
# 提取所有电话号码
text = "联系方式: 138-1234-5678, 139-8765-4321"
pattern = r'(\d{3})-(\d{4})-(\d{4})'
matches = re.findall(pattern, text)
for area, mid, last in matches:
    print(f"区号: {area}, 中间: {mid},  {last}")
    # 输出:
    # 区号: 138, 中间: 1234,  5678
    # 区号: 139, 中间: 8765,  4321

使用 finditer() 迭代匹配

import re
text = """姓名: 张三, 年龄: 25
姓名: 李四, 年龄: 30
姓名: 王五, 年龄: 28"""
pattern = r'姓名: (\w+), 年龄: (\d+)'
for match in re.finditer(pattern, text):
    name = match.group(1)
    age = match.group(2)
    print(f"姓名: {name}, 年龄: {age}")
    # 输出:
    # 姓名: 张三, 年龄: 25
    # 姓名: 李四, 年龄: 30
    # 姓名: 王五, 年龄: 28

复杂嵌套分组

import re
# 提取HTML中的标签内容和属性
html = '<a href="https://example.com" class="link">点击这里</a>'
pattern = r'<(\w+)\s+href="([^"]+)"\s+class="([^"]+)">([^<]+)</\1>'
match = re.search(pattern, html)
if match:
    tag = match.group(1)      # a
    href = match.group(2)      # https://example.com
    class_ = match.group(3)    # link
    content = match.group(4)   # 点击这里
    print(f"标签: {tag}, href: {href}, class: {class_}, 内容: {content}")

非捕获分组

import re
# 只想提取部分内容,不捕获某些分组
text = "苹果: 5元, 香蕉: 3元"
pattern = r'(?:苹果|香蕉): (\d+)元'
matches = re.findall(pattern, text)
for price in matches:
    print(f"价格: {price}元")
    # 输出:
    # 价格: 5元
    # 价格: 3元

实战:提取URL参数

import re
url = "https://example.com/api?name=张三&age=25&city=北京"
pattern = r'(?P<key>\w+)=(?P<value>[^&]+)'
params = {}
for match in re.finditer(pattern, url):
    key = match.group('key')
    value = match.group('value')
    params[key] = value
print(params)
# 输出: {'name': '张三', 'age': '25', 'city': '北京'}

分组提取的常用方法

import re
text = "我的电话号码是 010-12345678"
# 方法1:使用 groups() 获取所有分组
pattern = r'(\d{3})-(\d{8})'
match = re.search(pattern, text)
if match:
    print(match.groups())  # ('010', '12345678')
# 方法2:使用 groupdict() 获取命名分组
pattern = r'(?P<area>\d{3})-(?P<number>\d{8})'
match = re.search(pattern, text)
if match:
    print(match.groupdict())  # {'area': '010', 'number': '12345678'}

注意事项

  1. 分组编号:从1开始,group(0)group() 返回整个匹配
  2. 命名分组:提高可读性,推荐使用
  3. 非捕获分组:使用 减少不必要的分组
  4. 贪婪匹配:默认贪婪,使用 变成非贪婪模式

这些案例覆盖了正则分组提取的常见场景,你可以根据实际需求选择合适的提取方式。

抱歉,评论功能暂时关闭!