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

2024-05-20 11:37:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

因为\w\w表示两个字符,所以需要“he”和“ll”。但是为什么'el'和'lo'不匹配regex?

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

Tags: rehellolomatch字符elregexhe
3条回答

除了零长度断言外,输入中的字符将始终在匹配中使用。如果您希望在输入字符串中多次捕获某个字符,则需要在regex中使用零长度断言。

有几种零长度断言(例如^(输入/行的开始)、$(输入/行的结束)、\b(单词边界)),但是环视((?<=)正向后视和(?=)正向前视)是从输入捕获重叠文本的唯一方法。负环视((?<!)负环视后面,(?!)负环视前面)在这里不是很有用:如果它们断言为true,则内部捕获失败;如果它们断言为false,则匹配失败。这些断言的长度为零(如前所述),这意味着它们将在不使用输入字符串中的字符的情况下进行断言。如果断言通过,它们实际上将匹配空字符串。

应用上述知识,一个适用于您的案例的regex将是:

(?=(\w\w))

您可以使用new Python regex module,它支持重叠匹配。

>>> import regex as re
>>> match = re.findall(r'\w\w', 'hello', overlapped=True)
>>> print match
['he', 'el', 'll', 'lo']

默认情况下,findall不产生重叠匹配。但是,此表达式确实:

>>> re.findall(r'(?=(\w\w))', 'hello')
['he', 'el', 'll', 'lo']

这里(?=...)是一个lookahead assertion

(?=...) matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

相关问题 更多 >