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)  # 根据逗号和分号分割字符串
相关推荐
今天没有盐几秒前
Python 数据分析实战:多场景数据处理与可视化全解析
python·pycharm·编程语言
程序员三藏18 分钟前
如何用Postman做接口自动化测试?
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
n***271935 分钟前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
心无旁骛~37 分钟前
python多进程multiprocessing——spawn启动方式解析
开发语言·python
家家小迷弟1 小时前
docker容器内部安装python和numpy的方法
python·docker·numpy
conkl1 小时前
Python中的鸭子类型:理解动态类型的力量
开发语言·python·动态·鸭子类型·动态类型规划
故事挺秃然1 小时前
Python异步(Asyncio)(一)
服务器·网络·python
大飞记Python1 小时前
【2025全攻略】PyCharm专业版 / 社区版如何打开.db 数据库文件
数据库·python·sql·pycharm
坚持就完事了1 小时前
数据结构之链表
数据结构·python·算法·链表
木头左1 小时前
自动化超参搜索框架在PCA参数调优中的应用
python