Python3 - 字符串匹配和搜索

问题

匹配或者搜索特定模式的文本

解决方案

如果需要匹配的是字面字符串,只需要调用基本字符串方法就行, 比如 str.find()str.endswith()str.startswith() 或者类似的方法。

对于复杂的匹配需要使用正则表达式和 re 模块。 假设想匹配数字格式的日期字符串比如 11/27/2018,比如 :

import re

text1 = '11/27/2018'
text2 = 'Nov 27, 2018'

if re.match(r'\d+/\d+/\d+', text1):
    print('yes')
else:
    print('no')

if re.match(r'\d+/\d+/\d+', text2):
    print('yes')
else:
    print('no')

yes
no

如果想使用同一个模式去做多次匹配,需要先将模式字符串预编译为模式对象。比如:

com = re.compile(r'\d+/\d+/\d+')
if com.match(text1):
    print('yes')
else:
    print('no')

if com.match(text2):
    print('yes')
else:
    print('no')

yes
no

match() 总是从字符串开始去匹配,如果需要查找整个字符串进行匹配, 使用 findall()方法。比如:

text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
print(com.findall(text))

['11/27/2012', '3/13/2013']

在定义正则式的时候,通常会利用括号去捕获分组。比如:

recom = re.compile(r'(\d+)/(\d+)/(\d+)')
m = recom.match('12/11/2018')
print(m)
print(m.group(0))
print(m.group(1))
print(m.group(3))
print(m.groups())
print(recom.findall(text))

<_sre.SRE_Match object; span=(0, 10), match='12/11/2018'>
12/11/2018
12
2018
('12', '11', '2018')
[('11', '27', '2012'), ('3', '13', '2013')]

findall() 方法会搜索文本,以列表形式返回所有的匹配。 如果想以迭代方式返回匹配,可以使用 finditer() 方法来代替,比如:

for n in recom.finditer(text):
    print(n.group(0))

11/27/2012
3/13/2013

讨论

关于正则表达式理论的教程已经超出了本教程。 本教程阐述了使用re模块进行匹配和搜索文本的最基本方法。 核心步骤就是先使用 re.compile() 编译正则表达式字符串, 然后使用 match() , findall() 或者 finditer() 等方法。

如果你仅仅是做一次简单的文本匹配或搜索操作,可以略过编译部分,直接使用 re 模块级别的函数。

需要注意的是,如果做大量的匹配和搜索操作的话,最好先编译正则表达式,然后再重复使用它。 模块级别的函数会将最近编译过的模式缓存起来,因此并不会消耗太多的性能, 但是如果使用预编译模式的话,你将会减少查找和一些额外的处理损耗。

你可能感兴趣的:(Python3 - 字符串匹配和搜索)