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}'")
相关推荐
代码小书生14 分钟前
Matplotlib,Python 数据可视化核心库!
python·信息可视化·matplotlib
lzhdim28 分钟前
SharpCompress:跨平台的 C# 压缩与解压库
开发语言·c#
嘿嘿嘿x332 分钟前
Linux记录过程
linux·开发语言
默 语41 分钟前
Records、Sealed Classes这些新特性:Java真的变简单了吗?
java·开发语言·python
架构师老Y41 分钟前
013、数据库性能优化:索引、查询与连接池
数据库·python·oracle·性能优化·架构
止观止41 分钟前
拥抱 ESNext:从 TC39 提案到生产环境中的现代 JS
开发语言·javascript·ecmascript·esnext
Kel1 小时前
PydanticAI 源码深潜:类型安全依赖注入与图执行引擎的双核架构解析
人工智能·python·架构
卷心菜狗1 小时前
Python进阶-深浅拷贝辨析
开发语言·python
时寒的笔记1 小时前
js逆向7_案例惠nong网
android·开发语言·javascript
Thomas.Sir1 小时前
重构诊疗效率与精准度之【AI 赋能临床诊断与辅助决策从理论到实战】
人工智能·python·ai·医疗·诊断