Python正则模块re方法介绍

Python 的 re 模块提供了多种方法来处理正则表达式。以下是一些常用的方法及其功能介绍:

1. re.match()

在字符串的开始位置进行匹配。

python 复制代码
import re

pattern = r'\d+'
string = "123abc456"

match = re.match(pattern, string)
if match:
    print(f"匹配的字符串是: '{match.group()}'")

2. re.search()

在整个字符串中搜索模式的首次出现。

python 复制代码
import re

pattern = r'\d+'
string = "abc123def456"

match = re.search(pattern, string)
if match:
    print(f"匹配的字符串是: '{match.group()}'")

3. re.findall()

返回所有非重叠的匹配,以列表形式返回。

python 复制代码
import re

pattern = r'\d+'
string = "abc123def456ghi789"

matches = re.findall(pattern, string)
print(f"所有匹配项: {matches}")

4. re.finditer()

返回所有非重叠的匹配,以迭代器形式返回每个匹配的 MatchObject

python 复制代码
import re

pattern = r'\d+'
string = "abc123def456ghi789"

matches = re.finditer(pattern, string)
for match in matches:
    print(f"匹配的字符串是: '{match.group()}'")

5. re.sub()

使用指定的替换内容,替换所有匹配的子字符串。

python 复制代码
import re

pattern = r'\d+'
string = "abc123def456ghi789"
replacement = '#'

result = re.sub(pattern, replacement, string)
print(f"替换后的字符串: '{result}'")

6. re.subn()

re.sub() 类似,但返回一个包含新字符串和替换次数的元组。

python 复制代码
import re

pattern = r'\d+'
string = "abc123def456ghi789"
replacement = '#'

result, num_subs = re.subn(pattern, replacement, string)
print(f"替换后的字符串: '{result}'")
print(f"替换次数: {num_subs}")

7. re.split()

根据正则表达式模式分割字符串,返回一个列表。

python 复制代码
import re

pattern = r'\d+'
string = "abc123def456ghi789"

result = re.split(pattern, string)
print(f"分割结果: {result}")

8. re.compile()

预编译一个正则表达式模式,可以提高重复使用该模式的效率。

python 复制代码
import re

pattern = re.compile(r'\d+')
string = "abc123def456ghi789"

match = pattern.search(string)
if match:
    print(f"匹配的字符串是: '{match.group()}'")

9. re.escape()

对字符串中所有可能被解释为正则表达式特殊字符的字符进行转义。

python 复制代码
import re

string = "example.abc*123"

escaped_string = re.escape(string)
print(f"转义后的字符串: '{escaped_string}'")
相关推荐
额,不知道写啥。1 天前
P5354 [Ynoi Easy Round 2017] 由乃的 OJ
java·开发语言·算法
白太岁1 天前
通信:(5) 电路交换、报文交换与分组交换
运维·服务器·网络·网络协议
代码无bug抓狂人1 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
青桔柠薯片1 天前
Linux软件编程:线程和进程间通信
linux·开发语言·线程·进程
scott1985121 天前
Improving Classifier-Free Guidance of Flow Matching via Manifold Projection
人工智能·python·机器学习
foundbug9991 天前
基于C# WinForm实现串口数据读取与实时折线图显示
开发语言·c#
iOS开发上架1 天前
系统架构-信息系统
python·腾讯云
Lupino1 天前
从逻辑“脑裂”到 AI 重构:不到 2 美金解决物联网电位反转难题
python·物联网
feng68_1 天前
Nginx高性能Web服务器
linux·运维·服务器·nginx
青春不败 177-3266-05201 天前
最新AI赋能Python长时序植被遥感动态分析、物候提取、时空变异归因及RSEI生态评估
人工智能·python·生态学·植被遥感·遥感·物候提取