Python regex replace each match with itself plus a new line

Viewed 1868

I have a long regex with many alternations and I want to be able to replace each match from the regex with itself followed by a new line ('\n').

What is the most efficient way to do so with re.sub()?

Here is a simple example:

s = 'I want to be able to replace many words, especially in this sentence, since it will help me solve by problem. That makes sense right?'

pattern = re.compile(r'words[,]|sentence[,]|problem[.]')

for match in matches:
    re.sub(pattern, match + '\n', match)

I know this for loop will not work, I am just hoping to clarify what I am trying to solve here. Thanks in advance for any help. I may be missing something very straightforward.

3 Answers

the second parameter of re.sub can either be a string or a callable that takes in the match instance and returns a string. so do this

def break_line(match):
    return "\n" + match.group()

text = re.sub(pattern, break_line, text)
Related