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

How to remove last parentheses in string with its contents in python using regex?

Say we have a list of files like

(these aren’t symlinks btw, I’m just using the arrows to indicate input -> output relationship)

test(1) -> test
test2(1) -> test2
test3(note to self) (6) -> test3(note to self)

edit(not sure why there is a request to close for lack of focus. I’m literally giving you 3 specific test cases here)

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

We can make no assumptions about the rest of the string outside of the fact that there will be a set of parentheses at the end with something inside. So that means there might be parentheses before the last set of parentheses which should not be touched. only the last parentheses.

How to accomplish this with re python module?

>Solution :

I’d use a pattern such as:

import re

p = r'^([^\r\n]*)\([^)]*\)([^\r\n]*)$'
s = "test3(note to self)(6) -> test3(note to self) some text"
print(re.sub(p, r'\1\2', s))

Prints

test3(note to self)(6) -> test3 some text


^([^\r\n]*)\([^)]*\)([^\r\n]*)$

  • ^ and $ are the start and end anchors.
  • ([^\r\n]*) group is what you want to keep.
  • \([^)]*\) we want to discard this.
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