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}'")
相关推荐
人道领域19 分钟前
SSM框架从入门到入土(AOP面向切面编程)
java·开发语言
铅笔侠_小龙虾20 分钟前
Flutter 实战: 计算器
开发语言·javascript·flutter
全栈老石37 分钟前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
2的n次方_37 分钟前
Runtime 执行提交机制:NPU 硬件队列的管理与任务原子化下发
c语言·开发语言
梨落秋霜1 小时前
Python入门篇【模块/包】
python
珠海西格电力科技1 小时前
微电网能量平衡理论的实现条件在不同场景下有哪些差异?
运维·服务器·网络·人工智能·云计算·智慧城市
2501_944711431 小时前
JS 对象遍历全解析
开发语言·前端·javascript
释怀不想释怀1 小时前
Linux环境变量
linux·运维·服务器
zzzsde1 小时前
【Linux】进程(4):进程优先级&&调度队列
linux·运维·服务器
凡人叶枫1 小时前
C++中智能指针详解(Linux实战版)| 彻底解决内存泄漏,新手也能吃透
java·linux·c语言·开发语言·c++·嵌入式开发