代码详解之Python正则表达式的优秀使用指南2

紧接上一篇代码详解之Python正则表达式的优秀使用指南1
我们继续看一下:正则表达式函数

正则表达式函数:

目前为止,只使用了 re包中的findall 函数,其实还有很多其他函数。下面来逐个介绍。

1. findall
上面已经使用了 findall。这是我最常使用的一个。下面来正式认识一下这个函数吧。
输入:模式和测试字符串
输出:字符串列表。

#USAGE: 
pattern = r'[iI]t' 
string = "It was the best of times, it was the worst of times." 
matches = re.findall(pattern,string) 
for match in matches: 
print(match)------------------------------------------------------------ 
It 
it 

2.搜索
在这里插入图片描述
输入:模式和测试字符串

输出:首次匹配的位置对象。

#USAGE: 
pattern = r'[iI]t' 
string = "It was the best of times, it was the worst of times." 
location = re.search(pattern,string) 
print(location) 
------------------------------------------------------------ 
<_sre.SRE_Match object; span=(0, 2), match='It'> 

可以使用下面编程获取该位置对象的数据:

print(location.group()) 
------------------------------------------------------------ 
'It' 

3.替换
这个功能也很重要。当使用自然语言处理程序时,有时需要用X替换整数,或者可能需要编辑一些文件。任何文本编辑器中的查找和替换都可以做到。

输入:搜索模式、替换模式和目标字符串

输出:替换字符串

string = "It was the best of times, it was the worst of times." 
string = re.sub(r'times', r'life', string) 
print(string) 
------------------------------------------------------------ 
It was the best of life, it was the worst of life. 

正则表达式在数据操作、创建特性和寻找模式方面具有高度的灵活性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值