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)  # 根据逗号和分号分割字符串
相关推荐
AI蜗牛之家11 分钟前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk40 分钟前
python打卡第48天
开发语言·python
Eiceblue3 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550403 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂3 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP4 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@4 小时前
Python数据分析7
开发语言·python
老胖闲聊5 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点6 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI6 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python