Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading