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}'")
相关推荐
Blossom.1182 分钟前
基于区块链技术的供应链溯源系统:重塑信任与透明度
服务器·网络·人工智能·目标检测·机器学习·计算机视觉·区块链
Pacify_The_North2 分钟前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
xiaohanbao0917 分钟前
day29 python深入探索类装饰器
开发语言·python·学习·机器学习·pandas
wuqingshun31415929 分钟前
经典算法 (A/B) mod C
c语言·开发语言·c++·算法·蓝桥杯
半青年34 分钟前
Qt图表库推荐指南与分析
c语言·开发语言·javascript·c++·qt·信息可视化
艾米莉亚糖1 小时前
解决qt.network.ssl: QSslSocket::connectToHostEncrypted: TLS initialization failed
开发语言·qt·ssl
CryptoRzz1 小时前
股票数据源对接技术指南:印度尼西亚、印度、韩国
数据库·python·金融·数据分析·区块链
她说彩礼65万1 小时前
C# 中的锁
开发语言·c#
2302_809798321 小时前
【JavaWeb】JDBC
java·开发语言·servlet
烦躁的大鼻嘎1 小时前
【Linux】ELF与动静态库的“暗黑兵法”:程序是如何跑起来的?
linux·运维·服务器·c++·vscode·ubuntu