我有一个要在python中匹配的字符串数组。有没有一种方法可以不使用for循环?
到目前为止,我所看到的所有示例都类似于以下示例,在这些示例中,您必须遍历每个元素以找到匹配项:
import re
patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'
for pattern in patterns:
print 'Looking for "%s" in "%s" ->' % (pattern, text),
if re.search(pattern, text):
print 'found a match!'
else:
print 'no match'
无需使用for循环就可以做到这一点
与for循环不完全相同,但是使用来连接模式|
。a|b
比赛如果任一a
或b
匹配。
ultimate_pattern = '|'.join(patterns)
如果要获取所有匹配项,请使用findall
,但这种方式无法确定是哪个原始模式触发了匹配项,因为它返回了一个字符串列表。
re.findall(ultimate_pattern, text)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句