How to find overlapping matches with a regexp?

前端 未结 4 1606
悲&欢浪女
悲&欢浪女 2020-11-22 01:31
>>> match = re.findall(r\'\\w\\w\', \'hello\')
>>> print match
[\'he\', \'ll\']

Since \\w\\w means two characters, \'he\' and \'l

4条回答
  •  感情败类
    2020-11-22 02:22

    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'.

提交回复
热议问题