Python re模块:正则表达式综合指南
off999 2024-10-04 18:54 17 浏览 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:匹配 a 或 b 。
分组和捕获
括号 () 用于对比赛的某些部分进行分组和捕获。
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-.]+#39;
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 = "<div>content</div><div>another content</div>"
pattern_greedy = r'<div>.*</div>'
pattern_non_greedy = r'<div>.*?</div>'
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}")
输出:
贪婪匹配:['<div>内容</div><div>另一个内容</div>']
非贪婪匹配: ['<div>content</div>', '<div>another content</div>']
反向引用
反向引用允许您重用部分匹配文本。它们通过捕获组创建,然后使用 \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,}#39;
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']
相关推荐
- SPC相关的计算用excel和python实现【源码下载】
-
做SPC分析涉及到很多计算,比如CPK、PPK、概率图、PPM等等,网上很多公式,但具体实现却不是那么容易的。我们整理了这些用excel和python实现的代码。包括但不限于以下的内容:SPC分析中的...
- Python学不会来打我(34)python函数爬取百度图片_附源码
-
随着人工智能和大数据的发展,图像数据的获取变得越来越重要。作为Python初学者,掌握如何从网页中抓取图片并保存到本地是一项非常实用的技能。本文将手把手教你使用Python函数编写一个简单的百度图片...
- django python数据中心、客户、机柜、设备资源管理平台源码分享
-
先转发后关注,私信“资源”即可免费获取源码下载链接!本项目一个开源的倾向于数据中心运营商而开发的,拥有数据中心、客户、机柜、设备、跳线、物品、测试、文档等一些列模块的资源管理平台,解决各类资源集中管理...
- 熬夜也值得学习练手的108个Python项目(附源码),太实用了!
-
现在学编程的人越来越多,Python因为简单好上手、功能又强大,成了很多人的首选。不管是做数据分析、人工智能,还是写网络程序、自动化脚本,Python都能派上用场。而且它诞生的时间比网页还早,作为...
- 这五个办公室常用自动化工具python源码,复制代码就能用
-
办公室自动化现在能看这文章的恐怕大部分都是办公室久坐工作者,很多都有腰肌劳损、肩周炎等职业病,难道就不能有个工具缓解一下工作量吗?那么恭喜你点进了这篇文章,这篇文章将使用python直接实现五个常...
- 将python源代码封装成window可执行程序教程
-
将python源代码封装成window可执行程序教程点击键盘win+r打开运行框在运行框中输入cmd,进入到命令行。在命令行中输入piplist去查看当前电脑中所有的库检查是否有pyinstall...
- Python 爬虫如何爬取网页源码?(爬虫获取网页源代码)
-
下面教大家用几行代码轻松爬取百度首页源码。什么是urllib?urllib库是Python内置的HTTP请求库,它可以看做是处理URL的组件集合。urllib库包含了四大模块,具体如下:urllib....
- Python RPC 之 Thrift(python是做什么的)
-
thrift-0.12.0python3.4.3Thrift简介:Thrift是一款高性能、开源的RPC框架,产自Facebook后贡献给了Apache,Thrift囊括了整个RP...
- 用Python编写FPGA以太网MAC(附源码下载方式)
-
来源:EETOP作者:ccpp123略作了解后发现,MyHDL不是高层次综合,它实际上是用Python的一些功能实现了一个Verilog仿真器,能对用Python写的仿Verilog语言进行仿...
- python爬虫常用工具库总结(python爬虫工具下载)
-
说起爬虫,大家可能第一时间想到的是python,今天就简单为大家介绍下pyhton常用的一些库。请求库:实现基础Http操作urllib:python内置基本库,实现了一系列用于操作url的功能。...
- 手把手教你使用scrapy框架来爬取北京新发地价格行情(理论篇)
-
来源:Python爬虫与数据挖掘作者:霖hero大家好!我是霖hero。上个月的时候,我写了一篇关于IP代理的文章,手把手教你使用XPath爬取免费代理IP,今天在这里分享我的第二篇文章,希望大家可以...
- 2025年Python爬虫学习路线:第1阶段 爬虫基础入门开始
-
这个阶段的目标是让你熟悉Python的基础知识、了解HTTP请求和HTML是如何工作的,并最终完成你的第一个爬虫小项目——抓取名言!按照计划,我们首先要打好Python基础。Python就像是我们要...
- 如何入门 Python 爬虫?(python零基础爬虫)
-
1.很多人一上来就要爬虫,其实没有弄明白要用爬虫做什么,最后学完了却用不上。大多数人其实是不需要去学习爬虫的,因为工作所在的公司里有自己的数据库,里面就有数据来帮助你完成业务分析。什么时候要用到爬虫呢...
- 突破爬虫瓶颈:Python爬虫核心能力提升与案例实操
-
技术控必看!Python爬虫高手进阶全攻略,解锁数据处理高阶玩法在数字化时代,Python爬虫早已成为数据探索者手中的得力工具。从基础的网页抓取到复杂的数据处理,每一次技术升级都能带来新的突破。本文将...
- 网络爬虫开源框架(网络爬虫的框架)
-
目前开源爬虫下载框架是百花齐放,各个编程语言都有,以下主要介绍其中重要的几个:1)python:scrapy,pyspider,gcrawler2)Java:webmagic,WebCollector...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- SPC相关的计算用excel和python实现【源码下载】
- Python学不会来打我(34)python函数爬取百度图片_附源码
- django python数据中心、客户、机柜、设备资源管理平台源码分享
- 熬夜也值得学习练手的108个Python项目(附源码),太实用了!
- 这五个办公室常用自动化工具python源码,复制代码就能用
- 将python源代码封装成window可执行程序教程
- Python 爬虫如何爬取网页源码?(爬虫获取网页源代码)
- Python RPC 之 Thrift(python是做什么的)
- 用Python编写FPGA以太网MAC(附源码下载方式)
- python爬虫常用工具库总结(python爬虫工具下载)
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python自定义函数 (53)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python字典增加键值对 (53)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python人脸识别 (54)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)