Is there a way to refer to all the matched expression in re.sub without using a group?

Suppose I want to add all occurrences of a specific expression with a character such as \.

As sedit will look like.

 echo '__^^^%%%__FooBar' | sed 's/[_^%]/\\&/g'

Note that the character is &used to represent the original matching expression.

I looked at regular expressions and regex howto , but I don't see the equivalent of a character &that can be used to replace in a matched expression.

The only workaround I found was to use an extra set ()to group the expression and then reference the group as follows.

import re


line = "__^^^%%%__FooBar"
print re.sub("([_%^$])", r"\\\1", line)

?

+4
2

docs:

\g<0> , RE.

:

>>> print re.sub("[_%^$]", r"\\\g<0>", line)
\_\_\^\^\^\%\%\%\_\_FooBar
+8

, .

>>> print re.sub("(?=[_%^$])", r"\\", line)
\_\_\^\^\^\%\%\%\_\_FooBar
+4

All Articles