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}'")
相关推荐
AC赳赳老秦10 小时前
团队知识库搭建:用 OpenClaw 自动整理会议纪要、技术方案、故障复盘,同步到 Confluence / 语雀
开发语言·前端·python·github·visual studio·deepseek·openclaw
TBrL7UtdTELTTdut4BAL10 小时前
F7015TV3 光猫 Telnet 命令配置 DHCP 服务器
运维·服务器·网络
m0_6315298211 小时前
CSS如何利用Less快速生成颜色渐变背景_使用混合函数生成多样渐变
jvm·数据库·python
海兰11 小时前
将 Cursor 连接到生产日志:通过 Elastic MCP 服务器
运维·服务器·elasticsearch
计算机安禾11 小时前
【Linux从入门到精通】第41篇:Linux内核编译初体验——裁剪属于你自己的内核
linux·运维·服务器
handler0111 小时前
算法:图的基本概念
c语言·开发语言·c++·笔记·算法·图论
m0_6245785911 小时前
Laravel Blade 中高效筛选并限制关联分类数据的实践方案
jvm·数据库·python
byzh_rc11 小时前
[AI工具从入门到入土] 命令行
网络·人工智能·python·深度学习·matplotlib
NEGl DRYN11 小时前
index.php 和 php
开发语言·php
m0_5913647311 小时前
golang如何实现coredump分析_golang coredump分析实现策略
jvm·数据库·python