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 catch a repeating pattern with regex in a string?

I have a bunch of strings like this:
abc#axyz(abc#axyz#a#aabc)abc#axyz. What I need to do is remove all the #a that appear in the text between brackets, while those outside should remain. I’ve tried the following:

\((.*?)(#a)(.*?)\)

But it only catches the first repetition. What am I getting wrong? Thanks for any input!

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

>Solution :

Try (regex101 link):

import re

s = "abc#axyz(abc#axyz#a#aabc)abc#axyz"

out = re.sub(r"#a(?=.*\))(?!.*\()", "", s)
print(out)

Prints:

abc#axyz(abcxyzabc)abc#axyz
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