[Python] Using re.sub and replace with overall match

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I was just writing a program where I wanted to insert a newline after a specific pattern. The idea was to match the pattern and replace with the overall match (i.e. capture group \0) and \n.

    s = "abc"
    insert_newline_pattern = re.compile(r"b")
    re.sub(insert_newline_pattern, r"\0\n", s)


    However the output is a\x00\nc, reading \0 as a null character.

    I know that I can "simply" rewrite this as:

    s = "abc"
    insert_newline_pattern = re.compile(r"(b)")
    re.sub(insert_newline_pattern, r"\1\n", s)


    which outputs the desired ab\nc with the idea of wrapping the overall match into group \1 and substituting this. See also a Python regex101 demo.

    Is there a way to access the overall match in any way, similar to this PCRE regex101 demo in Python?

    Continue reading...

Compartilhe esta Página