pythonregexp-replace

Multiple groups replacemet with re.sub problem


I have this piece of code and I really have no idea why it is not working. I want to replace SOMETHING with NOTHING and delete a line with spaces and 50 in it.

Expected output:

NOTHING
1  1
2345234
abcdefg
foobar
wrwerdfdsf
import re

s = """SOMETHING
1  1
2345234
abcdefg
foobar
    50
wrwerdfdsf"""

repl = {'SOMETHING': 'NOTHING', '    50\n': ''}
n = re.sub(
    r'^(SOMETHING)\n.*\n.*\n.*\n.*\n.*\n.*\n.*\n(    50\n)',
    lambda x: repl[x.group()] if x.group() in repl else x.group(),
    s,
    flags=re.M
)

It replaces nothing. Maybe I need to write something in these brackets of x.group()?


Solution

  • This works for me. Do you strictly need the dictionary to manage the replacement terms?

    import re
    
    s = """SOMETHING
    1  1
    2345234
    abcdefg
    foobar
        50
    wrwerdfdsf"""
    
    
    n = re.sub(
        r'SOMETHING\n((?:.*\n){4})\s*50\n',
        r'NOTHING\n\1',
        s,
        flags=re.M
    )
    
    print(n)