python——re库

Python的re库是用于处理正则表达式的标准库,正则表达式是一种强大而灵活的文本处理工具,能够帮助你执行复杂的字符串匹配和替换操作。下面是一些基本的API及其使用场景和示例:

1. re.compile(pattern[, flags])

功能:编译正则表达式模式,生成一个正则表达式对象,可以用于后续的匹配操作。

使用场景:当你要多次使用同一个正则表达式时,预先编译可以提高效率。

示例

python 复制代码
import re

pattern = re.compile(r'\d+')  # 匹配一个或多个数字
match = pattern.match('123abc')
if match:
    print(match.group())  # 输出: 123

2. re.search(pattern, string[, flags])

功能:在字符串中搜索匹配正则表达式模式的第一个位置,返回一个匹配对象,如果没有找到匹配,则返回None。

使用场景:当你只想知道某个模式是否存在于字符串中,并且关心它的位置或相关信息时。

示例

python 复制代码
import re

result = re.search(r'\bword\b', 'An example word in a sentence.')
if result:
    print(f"Found at position: {result.start()}")  # 输出匹配的位置
else:
    print("Not found.")

3. re.match(pattern, string[, flags])

功能:尝试从字符串的起始位置匹配正则表达式模式,如果起始位置没有匹配,则返回None。

使用场景:当你只关心字符串开始处是否符合某种模式时。

示例

python 复制代码
import re

result = re.match(r'^Hello', 'Hello World!')
if result:
    print("Match found!")
else:
    print("No match at the beginning.")

4. re.findall(pattern, string[, flags])

功能:返回字符串中所有与模式匹配的非重叠匹配项列表。

使用场景:当你想要提取所有匹配的子串时。

示例

python 复制代码
import re

text = "The rain in Spain falls mainly in the plain."
matches = re.findall(r'\bain\b', text)
print(matches)  # 输出匹配的列表

5. re.sub(pattern, repl, string[, count, flags])

功能:将字符串中与模式匹配的部分替换为指定的字符串。

使用场景:需要批量替换文本中的某些模式时。

示例

python 复制代码
import re

text = "The price is $100 and the discount is $20."
new_text = re.sub(r'\$[0-9]+', 'USDxx', text)
print(new_text)  # 将所有金额替换成USDxx

6. re.split(pattern, string[, maxsplit, flags])

功能:根据匹配的模式分割字符串,返回分割后的子串列表。

使用场景:需要根据特定的模式来拆分字符串时。

示例

python 复制代码
import re

text = "one,two,three;four,five"
split_result = re.split(r'[;,]', text)
print(split_result)  # 根据逗号和分号分割字符串
相关推荐
amazinging2 分钟前
北京-4年功能测试2年空窗-报培训班学测开-第四十三天
python·学习
wgyang201636 分钟前
我的第一个LangFlow工作流——复读机
python
Zhen (Evan) Wang43 分钟前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya1 小时前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
赶紧去巡山1 小时前
pyhton基础【23】面向对象进阶四
python
旷世奇才李先生2 小时前
PyCharm 安装使用教程
ide·python·pycharm
这里有鱼汤2 小时前
“对象”?对象你个头!——Python世界观彻底崩塌的一天
后端·python
尘浮7282 小时前
60天python训练计划----day59
开发语言·python
wh39332 小时前
使用Python将PDF转换成word、PPT
python·pdf·word
船长@Quant2 小时前
数学视频动画引擎Python库 -- Manim Voiceover 语音服务 Speech Services
python·数学·manim·动画引擎·语音旁白