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

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

ztj100 2025-04-11 09:51 3 浏览 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']

相关推荐

Whoosh,纯python编写轻量级搜索工具

引言在许多应用程序中,搜索功能是至关重要的。Whoosh是一个纯Python编写的轻量级搜索引擎库,可以帮助我们快速构建搜索功能。无论是在网站、博客还是本地应用程序中,Whoosh都能提供高效的全文搜...

如何用Python实现二分搜索算法(python二分法查找代码)

如何用Python实现二分搜索算法二分搜索(BinarySearch)是一种高效的查找算法,适用于在有序数组中快速定位目标值。其核心思想是通过不断缩小搜索范围,每次将问题规模减半,时间复杂度为(O...

路径扫描 -- dirsearch(路径查找器怎么使用)

外表干净是尊重别人,内心干净是尊重自己,干净,在今天这个时代,应该是一种极高的赞美和珍贵。。。----网易云热评一、软件介绍Dirsearch是一种命令行工具,可以强制获取web服务器中的目录和文件...

78行Python代码帮你复现微信撤回消息!

来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。...

从零开始学习 Python!2《进阶知识》 Python进阶之路

欢迎来到Python学习的进阶篇章!如果你说已经掌握了基础语法,那么这篇就是你开启高手之路的大门。我们将一起探讨面向对象编程...

白帽黑客如何通过dirsearch脚本工具扫描和收集网站敏感文件

一、背景介绍...

Python之txt数据预定替换word预定义定位标记生成word报告(四)

续接Python之txt数据预定替换word预定义定位标记生成word报告(一)https://mp.toutiao.com/profile_v4/graphic/preview?pgc_id=748...

假期苦短,我用Python!这有个自动回复拜年信息的小程序

...

Python——字符串和正则表达式中的反斜杠(&#39;\&#39;)问题详解

在本篇文章里小编给大家整理的是关于Python字符串和正则表达式中的反斜杠('\')问题以及相关知识点,有需要的朋友们可以学习下。在Python普通字符串中在Python中,我们用'\'来转义某些普通...

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

Python...

Python中re模块详解(rem python)

在《...

python之re模块(python re模块sub)

re模块一.re模块的介绍1.什么是正则表达式"定义:正则表达式是一种对字符和特殊字符操作的一种逻辑公式,从特定的字符中,用正则表达字符来过滤的逻辑。(也是一种文本模式;)2、正则表达式可以帮助我们...

MySQL、PostgreSQL、SQL Server 数据库导入导出实操全解

在数字化时代,数据是关键资产,数据库的导入导出操作则是连接数据与应用场景的桥梁。以下是常见数据库导入导出的实用方法及代码,包含更多细节和特殊情况处理,助你应对各种实际场景。一、MySQL数据库...

Zabbix监控系统系列之六:监控 mysql

zabbix监控mysql1、监控规划在创建监控项之前要尽量考虑清楚要监控什么,怎么监控,监控数据如何存储,监控数据如何展现,如何处理报警等。要进行监控的系统规划需要对Zabbix很了解,这里只是...

mysql系列之一文详解Navicat工具的使用(二)

本章内容是系列内容的第二部分,主要介绍Navicat工具的使用。若查看第一部分请见:...

取消回复欢迎 发表评论: