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)  # 根据逗号和分号分割字符串
相关推荐
这里有鱼汤25 分钟前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩10 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在15 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP17 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20231 天前
Python 模式匹配match case
前端·后端·python
这里有鱼汤1 天前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员