紧接上一篇代码详解之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.
正则表达式在数据操作、创建特性和寻找模式方面具有高度的灵活性。