How to find overlapping matches with a regexp?

前端 未结 4 1602
悲&欢浪女
悲&欢浪女 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:09

    Except for zero-length assertion, character in the input will always be consumed in the matching. If you are ever in the case where you want to capture certain character in the input string more the once, you will need zero-length assertion in the regex.

    There are several zero-length assertion (e.g. ^ (start of input/line), $ (end of input/line), \b (word boundary)), but look-arounds ((?<=) positive look-behind and (?=) positive look-ahead) are the only way that you can capture overlapping text from the input. Negative look-arounds ((? negative look-behind, (?!) negative look-ahead) are not very useful here: if they assert true, then the capture inside failed; if they assert false, then the match fails. These assertions are zero-length (as mentioned before), which means that they will assert without consuming the characters in the input string. They will actually match empty string if the assertion passes.

    Applying the knowledge above, a regex that works for your case would be:

    (?=(\w\w))
    

提交回复
热议问题