请容忍我这一点,因为我可能解释得不太好。
我有一个简单的正则表达式:
^(The\s)?(cat\s)?(sat\s)?(on\s)?(the\s)?(mat\.)?将文本转换为
The cat sat on the mat.成功通过。太棒了!
然而,我所追求的是一种找出regex在哪些组上失败的方法。例如:
The cat sat on the mat # fails on group 6 (no period)
The cat sat on teh mat. # fails on group 5 (teh instead of the)
The kat sat on the mat. # fails on group 2 (kat instead of cat)后一个例子在其他方面都很好,只是有一个组失败了。我的问题是:在Python中,有没有一种方法可以确定该字符串是否会在逐个组的基础上成功-而不必在每个组中创建regex fir的迭代?
发布于 2018-03-20 22:42:33
如果只想知道第一个故障发生在哪里,可以使用re.findall()
import re
regex = r'^(The\s)?(cat\s)?(sat\s)?(on\s)?(the\s)?(mat\.)?'
text = ''The cat sat on teh mat.'
re.findall(regex, text)
# [('The ', 'cat ', 'sat ', 'on ', '', '')]因此,您可以通过执行以下操作来找出第一次失败的索引:
re.findall(regex, text)[0].index('')
# 4(请注意,如果您的正则表达式中有重叠匹配、回溯或其他更不寻常的模式,则此方法可能没有用)。
https://stackoverflow.com/questions/49386824
复制相似问题