如何找到与regexp重叠的匹配?

如何找到与regexp重叠的匹配?

>>> match = re.findall(r'\w\w', 'hello')>>> print match['he', 'll']

因为\w意味着两个字符,所以需要“he”和“ll”。但是为什么‘el’和‘lo’匹配判决吗?

>>> match1 = re.findall(r'el', 'hello')>>> print match1['el']>>>


波斯汪
浏览 665回答 3
3回答

杨魅力

findall默认情况下不会产生重叠匹配。然而,这个短语确实:>>> re.findall(r'(?=(\w\w))', 'hello')['he', 'el', 'll', 'lo']这里(?=...)是前瞻性断言:(?=...)匹配...匹配Next,但不使用任何字符串。这被称为前瞻性断言。例如,Isaac (?=Asimov)将匹配'Isaac '但前提是'Asimov'.

潇潇雨雨

您可以使用新Python regex模块,它支持重叠匹配。>>> import regex as re>>> match = re.findall(r'\w\w', 'hello', overlapped=True)>>> print match['he', 'el', 'll', 'lo']
打开App,查看更多内容
随时随地看视频慕课网APP