一文读懂Python re正则表达式模块

正则表达式

正则表达式是一种描述文本模式的语言,Python通过re模块提供了对正则表达式的支持,使其成为文本处理、数据洗白和信息提取的强大工具。

正则表达式基本语法

元字符 描述
. 匹配任意单个字符(除了换行符)
^ 匹配字符串的开头
$ 匹配字符串的结尾
* 匹配前面的元素零次或多次
+ 匹配前面的元素一次或多次
? 匹配前面的元素零次或一次
[] 匹配方括号中的任意一个字符
() 分组和捕获
\d 匹配数字,等价于[0-9]
\w 匹配字母、数字或下划线,等价于[a-zA-Z0-9_]
\s 匹配空白字符

re模块核心函数

  • match(): 从字符串开头匹配
python 复制代码
import re

text = "Hello, World!"
match = re.match(r'Hello', text)
if match:
    print("匹配成功:", match.group())  # 输出: 匹配成功: Hello
  • search(): 搜索整个字符串
python 复制代码
text = "Price: $19.99"
match = re.search(r'\$\d+\.\d+', text)
if match:
    print("找到价格:", match.group())  # 输出: 找到价格: $19.99
  • findall():找到所有匹配项
python 复制代码
text = "Email1: user@example.com, Email2: admin@company.net"
emails = re.finditer(r'[\w.-]+@[\w.-]+\.\w+', text)
for email in emails:
    print("找到邮箱:", email.group())
  • finditer():返回匹配的迭代器
python 复制代码
text = "Email1: user@example.com, Email2: admin@company.net"
emails = re.finditer(r'[\w.-]+@[\w.-]+\.\w+', text)
for email in emails:
    print("找到邮箱:", email.group())
  • sub():替换匹配的文本
python 复制代码
text = "Phone numbers: 123-456-7890, 987-654-3210" masked = re.sub(r'(\d{3})-(\d{3})-(\d{4})', r'\1-***-\4', text) print("掩码后的号码:", masked) # 输出: 掩码后的号码: 123-***-7890, 987-***-3210

正则表达式进阶技巧

  • 分组与捕获 使用圆括号() 进行分组,分组可以被引用和捕获
python 复制代码
text = "Date: 2023-11-15"
match = re.match(r'(\d{4})-(\d{2})-(\d{2})', text)
if match:
    year, month, day = match.groups()
    print(f"年: {year}, 月: {month}, 日: {day}")  # 输出: 年: 2023, 月: 11, 日: 15

match.group()方法是一个管理捕获的一个核心工具,用于捕获匹配对象中的特定部分。当正则表达式成功匹配文本后,match.group()方法允许提取出具体的内容,无论是整个匹配结果还是特定的捕获组。

基本语法: match.group() - 无参数:返回整个匹配的字符串 - 整数参数:返回指定捕获的内容 - 多个参数:返回多个捕获的元祖 - 命名组参数:返回指定命名组的内容

python 复制代码
import re

# 示例文本
text = "Hello, my email is user@example.com and phone is 123-456-7890."

# 定义一个包含多个捕获组的正则表达式
pattern = r'(\w+)@(\w+\.\w+)|(\d{3})-(\d{3})-(\d{4})'
match = re.search(pattern, text)

if match:
    # 0. 检查匹配是否成功
    print("匹配成功!")
    
    # 1. 无参数:获取整个匹配内容
    print("整个匹配:", match.group())  # 输出: user@example.com
    
    # 2. 单个整数参数:获取特定捕获组
    print("捕获组1:", match.group(1))  # 输出: user (邮箱用户名)
    print("捕获组2:", match.group(2))  # 输出: example.com (邮箱域名)
    
    # 3. 多个参数:获取多个捕获组
    print("捕获组1和2:", match.group(1, 2))  # 输出: ('user', 'example.com')
    
    # 4. 使用groups()方法获取所有捕获组
    print("所有捕获组:", match.groups())  # 输出: ('user', 'example.com', None, None, None)
    
    # 5. 捕获组索引从1开始,0表示整个匹配
    print("捕获组0:", match.group(0))  # 输出: user@example.com
相关推荐
IT_陈寒3 分钟前
Vite 5年迭代揭秘:3个核心优化让你的项目构建速度提升200%
前端·人工智能·后端
拾贰_C27 分钟前
【SpringBoot】前后端联动实现条件查询操作
java·spring boot·后端
catchadmin2 小时前
PHP 快速集成 ChatGPT 用 AI 让你的应用更聪明
人工智能·后端·chatgpt·php
callJJ6 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di
你的人类朋友8 小时前
JWT的组成
后端
北风朝向9 小时前
Spring Boot参数校验8大坑与生产级避坑指南
java·spring boot·后端·spring
canonical_entropy10 小时前
一份关于“可逆计算”的认知解码:从技术细节到哲学思辨的完整指南
后端·低代码·deepseek
趙卋傑10 小时前
项目发布部署
linux·服务器·后端·web
数据知道11 小时前
Go基础:Go语言能用到的常用时间处理
开发语言·后端·golang·go语言
不爱编程的小九九12 小时前
小九源码-springboot048-基于spring boot心理健康服务系统
java·spring boot·后端