Refenecing named capture groups in re.sub deprecated?

The latest python documentation says:

Ways to reference it [meaning captured group] […] in a string passed to the repl argument of re.sub():

  • \g<quote>
  • \g<1>
  • \1

Yet, pytest says this in one of my tests:

DeprecationWarning: invalid escape sequence \g
msg=re.sub(color_regex, “\g<msg>”, record),

What is the non-deprecated way to refer to a named capture group? I can’t seem to find it.

The warning you are seeing is unrelated to re.sub or pytest, it is due to the backslash in the string.
If you want to have a string containing a backslash then the letter “g”, you have to escape the backslash itself: "\\g", or use a raw string: r"\g".

2 Likes