eugene y eugene y - 11 months ago 32
Perl Question

Is there any equivalent to the Perl regexes' \K backslash sequence in Python?

Perl's regular expressions have the

backslash sequence:


This appeared in perl 5.10.0. Anything matched left of
is not
included in
, and will not be replaced if the pattern is used in a
substitution. This lets you write
instead of
s/(PAT1) PAT2/${1}REPL/x
s/(?<=PAT1) PAT2/REPL/x

Mnemonic: Keep.

Is there anything equivalent in Python?

Answer Source

The proposed replacement to the Python re module, available from pypi under the name regex, has this feature. Its canonical source repository and bug tracker are in bitbucket.

This was added in late 2015, in ticket 151; taking an example of its use from that ticket:

import regex as mrab
>>> bsk = mrab.compile(r'start=>\K.*')
>>> print('boring stuff start=>interesting stuff'))
<regex.Match object; span=(20, 37), match='interesting stuff'>