如何找到与正则表达式重叠的匹配项? [英] How to find overlapping matches with a regexp?

查看:77
本文介绍了如何找到与正则表达式重叠的匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>match = re.findall(r'\w\w', '你好')>>>打印匹配['地狱']

由于 \w\w 表示两个字符,因此需要 'he' 和 'll'.但是为什么 'el' 和 'lo' 匹配正则表达式?

<预><代码>>>>match1 = re.findall(r'el', '你好')>>>打印匹配 1['el']>>>

解决方案

findall 默认情况下不会产生重叠匹配.然而,这个表达式确实:

<预><代码>>>>re.findall(r'(?=(\w\w))', '你好')['he', 'el', 'll', 'lo']

这里 (?=...) 是一个 前瞻断言:

<块引用>

(?=...) 如果 ... 匹配下一个,则匹配,但不消耗任何细绳.这称为先行断言.例如,Isaac (?=Asimov) 仅在 'Asimov' 后跟 'Isaac' 时匹配.

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

Since \w\w means two characters, 'he' and 'll' are expected. But why do 'el' and 'lo' not match the regex?

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

解决方案

findall doesn't yield overlapping matches by default. This expression does however:

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

Here (?=...) is a 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'.

这篇关于如何找到与正则表达式重叠的匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆