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

re.sub not replacing using REGEX group matching

I am trying to match and replace all content tagged inside brackets with the following code:

content = 'Should replace [obj[text]obj] inside [loc[brackets]loc]'
pattern = re.compile(r"\[([A-Za-z0-9]+)(\[(.*?)\])([A-Za-z0-9]+)\]")
for match in pattern.finditer(content):
  print(match.group(2))
  re.sub(match.group(2), 'xxx', content)

However it keeps returning the very same original string. If I go like:

new=re.sub(match.group(2), 'xxx', content)

It returns something really random I can’t still acount for. It gets me puzzled because the print in line 4 shows the findigs are correct.

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

Many thanks in advance.

>Solution :

You shouldn’t be looping. Just call re.sub() once, and it will replace all occurrences of the regular expression. Use back-references in the replacement string to copy parts of the match into the replacement.

new = re.sub(pattern, r'[\1xxx\4]', content);

DEMO

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