Problem to replace all strings in a line which have a specific pattern in python

Let me start by saying that i am new to python.

line = "lmn = abc(xyz)/123/.../abc(123)"

line = "abc(xyz) = dlf/hmn/abc(fdg)"

The pattern replacement example I am trying is abc(xxx) = $xxx something along these lines.

The regex I have created is (abc\()(.*?)(\)) –> this is working fine.
Now how do I ensure the replacement happens in all the places in a line as the (.*?) is different at different places in a line.

I found that we have re.findall(pattern, string, flags=0) which will return a tuple which I can use to construct a table and go with line replacing.
Is there a better way of substituting the pattern everywhere?

tmp = re.sub('(abc\\()(.*?)(\\))', '$' **group(1) content**, line , count=???)

The problem with above is I cant use the obj within the re.sub I call

in perl it was simple one line regex

 =~ s/(abc\\()(.*?)(\\))/(\\$)$2/g

Can you please point me to a document for a module or any regex module in python that I can use for this. Btw..I am using python 3.6

>Solution :

You can use \<capture group number> in the replacement pattern for sub to insert a capture group.

So if I’m understanding your question correctly, this is what you’re looking for:

import re

line1 = "lmn = abc(xyz)/123/.../abc(123)"
line2 = "abc(xyz) = dlf/hmn/abc(fdg)"

# I've simplified the pattern a little to only use two capture groups.
pattern = re.compile(r"(abc\((.*?)\))")

# This is the pattern to replace with: a dollar sign followed by the
# contents of capture group 2.
replacement_pattern = r"$\2"

print(pattern.sub(replacement_pattern, line1)) # lmn = $xyz/123/.../$123
print(pattern.sub(replacement_pattern, line2)) # $xyz = dlf/hmn/$fdg

Leave a Reply