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)  # 根据逗号和分号分割字符串
相关推荐
高频交易dragon1 天前
5分钟和30分钟联立进行缠论信号分析
开发语言·python
0思必得01 天前
[Web自动化] 开发者工具应用(Application)面板
运维·前端·python·自动化·web自动化·开发者工具
我是华为OD~HR~栗栗呀1 天前
华为OD-C面经-23届学院哦
java·c++·python·华为od·华为·面试
xiaozi41201 天前
Ruey S. Tsay《时间序列分析》Python实现笔记:综合与应用
开发语言·笔记·python·机器学习
Aspect of twilight1 天前
PyTorch DDP分布式训练Pytorch代码讲解
人工智能·pytorch·python
@游子1 天前
Python学习笔记-Day5
笔记·python·学习
棒棒的皮皮1 天前
【OpenCV】Python图像处理之数字水印
图像处理·python·opencv·计算机视觉
tomeasure1 天前
INTERNAL ASSERT FAILED at “/pytorch/c10/cuda/CUDACachingAllocator.cpp“:983
人工智能·pytorch·python·nvidia
追光天使1 天前
装饰器的作用
python·装饰器
一瞬祈望1 天前
【环境配置】Windows 下使用 Anaconda 创建 Python 3.8 环境 + 安装 PyTorch + CUDA(完整教程)
pytorch·windows·python