百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Python re模块:正则表达式综合指南

ztj100 2025-04-11 09:51 11 浏览 0 评论

Python re 的模块提供对正则表达式 (regex) 的支持,正则表达式是匹配文本中模式的强大工具。正则表达式广泛用于数据验证、文本处理等。

快速入门re

要在 Python 中使用正则表达式,需要导入以下 re 模块:

import re

re 模块提供了广泛的模式匹配、搜索、拆分和替换文本的功能。

正则表达式的基本语法

正则表达式由定义搜索模式的字符序列组成。以下是一些基本元素:

  • 文字字符:匹配自己。例如, a 匹配字符“a”。
  • 元字符:具有特殊含义,例如 . (除换行符外的任何字符)、 ^ (字符串开头)、 $ (字符串结尾)、 * (0 次或更多次)、 + (1 次或多次出现)、 ? (0 或 1 次出现)、 {} (特定出现次数)、 [] (字符类)、 | (或)、 () (分组)。

常用re功能

re.match()

re.match() 函数检查模式是否与字符串开头的模式匹配。

import re
pattern = r'\d+'
text = "123abc"
match = re.match(pattern, text)
if match:
    print(f"Matched: {match.group()}")
else:
    print("No match")

输出:

匹配: 123

re.search()

re.search() 函数扫描整个字符串以查找匹配项。

import re
pattern = r'\d+'
text = "abc123xyz"
search = re.search(pattern, text)
if search:
    print(f"Found: {search.group()}")
else:
    print("Not found")

输出:
找到: 123

re.findall()

re.findall() 函数以列表形式返回字符串中模式的所有非重叠匹配项。

import re
pattern = r'\d+'
text = "abc123xyz456"
matches = re.findall(pattern, text)
print(f"Matches: {matches}")

输出:
比赛: ['123', '456']

re.finditer()

re.finditer() 函数返回一个迭代器,为所有非重叠匹配项生成匹配对象。

import re
pattern = r'\d+'
text = "abc123xyz456"
matches = re.finditer(pattern, text)
for match in matches:
    print(f"Match: {match.group()}")

输出:
匹配: 123
匹配: 456

re.sub()

re.sub() 函数将匹配项替换为指定的替换字符串。

import re
pattern = r'\d+'
replacement = '#'
text = "abc123xyz456"
result = re.sub(pattern, replacement, text)
print(f"Result: {result}")

输出:
结果:abc#xyz#

re.split()

re.split() 函数按模式的出现次数拆分字符串。

import re
pattern = r'\d+'
text = "abc123xyz456"
split_result = re.split(pattern, text)
print(f"Split result: {split_result}")

输出:

拆分结果: ['abc', 'xyz', '']

特殊序列和字符类

正则表达式为更复杂的模式提供特殊的序列和字符类。

  • \d:匹配任何数字。等效于 [0-9]
  • \D:匹配任何非数字。
  • \w:匹配任何字母数字字符。等效于 [a-zA-Z0-9_]
  • \W:匹配任何非字母数字字符。
  • \s:匹配任何空格字符。
  • \S:匹配任何非空格字符。
  • [abc]:匹配括号内的任何字符。
  • [^abc]:匹配括号内的任何字符。
  • a|b:匹配 ab

分组和捕获

括号 () 用于对比赛的某些部分进行分组和捕获。

import re
pattern = r'(\d+)-(\w+)'
text = "123-abc"
match = re.search(pattern, text)
if match:
    print(f"Group 1: {match.group(1)}")
    print(f"Group 2: {match.group(2)}")

输出:

第 1 组:123
第 2 组:abc

前瞻和后瞻

Lookahead 和 lookbehind 断言允许在不消耗字符串字符的情况下创建更复杂的模式。

  • Lookahead (?=...):断言断言后面的内容为 true。
import re
pattern = r'\d+(?=abc)'
text = "123abc456"
match = re.search(pattern, text)
if match:
    print(f"Lookahead match: {match.group()}")

输出:

前瞻匹配: 123

  • 负面展望(?!...):断言断言后面的内容是错误的。
import re
pattern = r'\d+(?!abc)'
text = "123def456abc"
matches = re.findall(pattern, text)
print(f"Negative lookahead matches: {matches}")

输出:

负面前瞻匹配: ['123', '456']

  • Lookbehind (?<=...):断言断言之前的内容为真。
import re
pattern = r'(?<=abc)\d+'
text = "abc123def456"
match = re.search(pattern, text)
if match:
    print(f"Lookbehind match: {match.group()}")

输出:

后视匹配:123

  • 否定后视 (?<!...):断言断言之前的内容是错误的。
import re
pattern = r'(?<!abc)\d+'
text = "abc123def456"
matches = re.findall(pattern, text)
print(f"Negative lookbehind matches: {matches}")

输出:

负后视匹配:['456']

实例

电子邮件验证

正则表达式的常见用途是电子邮件验证。

import re
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+
text = "example@example.com" match = re.match(pattern, text) if match: print("Valid email") else: print("Invalid email")

输出:

有效的电子邮件

电话号码提取

使用正则表达式可以很容易地从文本中提取电话号码。

import re
pattern = r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'
text = "Contact me at 123-456-7890 or 987.654.3210"
matches = re.findall(pattern, text)
print(f"Phone numbers: {matches}")

输出:

电话号码: ['123–456–7890', '987.654.3210']

解析日志

正则表达式通常用于分析日志文件中的特定信息。

import re
pattern = r'(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}),(\d+) - (\w+) - (.*)'
log_entry = "2024-06-03 12:34:56,789 - INFO - This is a log message"
match = re.match(pattern, log_entry)
if match:
    print(f"Date: {match.group(1)}")
    print(f"Time: {match.group(2)}")
    print(f"Milliseconds: {match.group(3)}")
    print(f"Level: {match.group(4)}")
    print(f"Message: {match.group(5)}")

输出:
日期: 2024–06–03
时间: 12:34:56
毫秒: 789
级别: INFO

消息:这是一条日志消息

正则表达式中的高级主题

为了扩展我们对该 re 模块的理解,让我们深入研究一些高级主题和技术。其中包括更复杂的模式匹配、处理不同类型的输入数据以及优化使用正则表达式时的性能。

高级模式匹配

非贪婪量词

默认情况下,正则表达式中的量词是贪婪的,这意味着它们会尝试匹配尽可能多的文本。非贪婪量词尽可能少地匹配文本。

  • 贪婪: .* 尽可能多地匹配。
  • 非贪婪: .*? 尽可能少地匹配。
import re
text = "
content
another content
" pattern_greedy = r'
.*
' pattern_non_greedy = r'
.*?
' match_greedy = re.findall(pattern_greedy, text) match_non_greedy = re.findall(pattern_non_greedy, text) print(f"Greedy match: {match_greedy}") print(f"Non-Greedy match: {match_non_greedy}")

输出:

贪婪匹配:['

内容
另一个内容
']

非贪婪匹配: ['
content
', '
another content
']

反向引用

反向引用允许您重用部分匹配文本。它们通过捕获组创建,然后使用 \1\2 等进行引用。

import re
pattern = r'(\b\w+)\s+\1'
text = "hello hello world world"
matches = re.findall(pattern, text)
print(f"Backreferences match: {matches}")

输出:

反向引用匹配:['hello', 'world']

条件表达式

正则表达式中的条件表达式通过测试特定捕获组的存在来允许更复杂的逻辑。

import re
pattern = r'(a)?b(?(1)c|d)'
text1 = "abc"
text2 = "bd"
match1 = re.match(pattern, text1)
match2 = re.match(pattern, text2)
print(f"Conditional match 1: {match1.group() if match1 else 'No match'}")
print(f"Conditional match 2: {match2.group() if match2 else 'No match'}")

输出:

条件匹配 1:abc
条件匹配 2:bd

处理不同类型的输入数据

多行字符串

使用多行字符串时, re.MULTILINE 标志允许 ^$ 分别匹配每行的开头和结尾。

import re
pattern = r'^\d+'
text = """123
abc
456
def"""
matches = re.findall(pattern, text, re.MULTILINE)
print(f"Multiline matches: {matches}")

输出:

多行匹配: ['123', '456']

Dotall 模式

re.DOTALL 标志允许 . 字符匹配换行符,从而可以匹配整个文本,包括换行符。

import re
pattern = r'.*'
text = """line1
line2
line3"""
match = re.match(pattern, text, re.DOTALL)
print(f"Dotall match: {match.group() if match else 'No match'}")

输出:

Dotall 匹配:line1
2号线
3号线

Unicode 支持

re.UNICODE 标志支持完全 Unicode 匹配,这对于处理国际文本特别有用。

import re
pattern = r'\w+'
text = "Café Müller"
matches = re.findall(pattern, text, re.UNICODE)
print(f"Unicode matches: {matches}")

输出:

Unicode 匹配: ['Café', 'Müller']

优化正则表达式性能

编译正则表达式

编译正则表达式可以在多次使用同一模式时提高性能。

import re
pattern = re.compile(r'\d+')
text = "123 456 789"
matches = pattern.findall(text)
print(f"Compiled matches: {matches}")

输出:

编译匹配项: ['123', '456', '789']

使用原始字符串

原始字符串(前缀 r )可防止 Python 将反斜杠解释为转义字符,从而更轻松地编写和读取正则表达式。

import re
pattern = r'\b\d{3}\b'
text = "100 200 300"
matches = re.findall(pattern, text)
print(f"Raw string matches: {matches}")

输出:

原始字符串匹配:['100', '200', '300']

高级实例

提取 URL

从文本中提取 URL 是正则表达式的常见用例。

import re
pattern = r'https?://[^\s<>"]+|www\.[^\s<>"]+'
text = "Visit https://www.linkedin.com/in/gaurav-kumar007/ and https://topmate.io/gaurav_kumar_quant for more info. Also check https://docs.python.org/3/howto/regex.html."
matches = re.findall(pattern, text)
print(f"URLs: {matches}")

输出:

网址: ['
https://www.linkedin.com/in/gaurav-kumar007/', '
https://topmate.io/gaurav_kumar_quant', '
https://docs.python.org/3/howto/regex.html.']

验证密码

密码验证通常需要复杂的规则,这些规则可以使用正则表达式来实现。

import re
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}
passwords = ["Password1!", "pass", "PASSWORD1!", "Pass1!", "ValidPass123!"] for pwd in passwords: match = re.match(pattern, pwd) print(f"Password: {pwd} - {'Valid' if match else 'Invalid'}")

输出:

密码:Password1!— 有效
密码:pass — 无效

密码:PASSWORD1!— 无效

密码:Pass1!— 无效

密码:ValidPass123!— 有效

数据清洗

正则表达式对于清理和转换数据非常有用。例如,从文本中删除多余的空格或不需要的字符。

import re
text = "This    is  a  test   string."
# Remove extra spaces
cleaned_text = re.sub(r'\s+', ' ', text).strip()
print(f"Cleaned text: {cleaned_text}")

输出:

已清理的文本:这是一个测试字符串。

解析日期

使用正则表达式可以有效地从文本中提取和格式化日期。

import re
pattern = r'(\d{4})-(\d{2})-(\d{2})'
text = "Dates: 2024-06-03, 2023-12-25, and 2025-01-01."
matches = re.findall(pattern, text)
formatted_dates = [f"{year}/{month}/{day}" for year, month, day in matches]
print(f"Formatted dates: {formatted_dates}")

输出:

格式日期: ['2024/06/03', '2023/12/25', '2025/01/01']

相关推荐

如何将数据仓库迁移到阿里云 AnalyticDB for PostgreSQL

阿里云AnalyticDBforPostgreSQL(以下简称ADBPG,即原HybridDBforPostgreSQL)为基于PostgreSQL内核的MPP架构的实时数据仓库服务,可以...

Python数据分析:探索性分析

写在前面如果你忘记了前面的文章,可以看看加深印象:Python数据处理...

CSP-J/S冲奖第21天:插入排序

...

C++基础语法梳理:算法丨十大排序算法(二)

本期是C++基础语法分享的第十六节,今天给大家来梳理一下十大排序算法后五个!归并排序...

C 语言的标准库有哪些

C语言的标准库并不是一个单一的实体,而是由一系列头文件(headerfiles)组成的集合。每个头文件声明了一组相关的函数、宏、类型和常量。程序员通过在代码中使用#include<...

[深度学习] ncnn安装和调用基础教程

1介绍ncnn是腾讯开发的一个为手机端极致优化的高性能神经网络前向计算框架,无第三方依赖,跨平台,但是通常都需要protobuf和opencv。ncnn目前已在腾讯多款应用中使用,如QQ,Qzon...

用rust实现经典的冒泡排序和快速排序

1.假设待排序数组如下letmutarr=[5,3,8,4,2,7,1];...

ncnn+PPYOLOv2首次结合!全网最详细代码解读来了

编辑:好困LRS【新智元导读】今天给大家安利一个宝藏仓库miemiedetection,该仓库集合了PPYOLO、PPYOLOv2、PPYOLOE三个算法pytorch实现三合一,其中的PPYOL...

C++特性使用建议

1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...

Qt4/5升级到Qt6吐血经验总结V202308

00:直观总结增加了很多轮子,同时原有模块拆分的也更细致,估计为了方便拓展个管理。把一些过度封装的东西移除了(比如同样的功能有多个函数),保证了只有一个函数执行该功能。把一些Qt5中兼容Qt4的方法废...

到底什么是C++11新特性,请看下文

C++11是一个比较大的更新,引入了很多新特性,以下是对这些特性的详细解释,帮助您快速理解C++11的内容1.自动类型推导(auto和decltype)...

掌握C++11这些特性,代码简洁性、安全性和性能轻松跃升!

C++11(又称C++0x)是C++编程语言的一次重大更新,引入了许多新特性,显著提升了代码简洁性、安全性和性能。以下是主要特性的分类介绍及示例:一、核心语言特性1.自动类型推导(auto)编译器自...

经典算法——凸包算法

凸包算法(ConvexHull)一、概念与问题描述凸包是指在平面上给定一组点,找到包含这些点的最小面积或最小周长的凸多边形。这个多边形没有任何内凹部分,即从一个多边形内的任意一点画一条线到多边形边界...

一起学习c++11——c++11中的新增的容器

c++11新增的容器1:array当时的初衷是希望提供一个在栈上分配的,定长数组,而且可以使用stl中的模板算法。array的用法如下:#include<string>#includ...

C++ 编程中的一些最佳实践

1.遵循代码简洁原则尽量避免冗余代码,通过模块化设计、清晰的命名和良好的结构,让代码更易于阅读和维护...

取消回复欢迎 发表评论: