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

Python: re.sub removing words between two delimiters under different cases

I have a string that contains patterns like

"something [[remove|keep]] something [[keep]] something [[remove|remove|keep]] something" 

How can I use re.sub() or other methods to edit this string to

"something keep something keep something keep something"

or

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

"something [[keep]] something [[keep]] something [[keep]] something". 

(I can remove the [[ ]]s afterward.)

I tried using for-loop to hard code it, but the string is too long and takes a long time to run.

>Solution :

You can use the regular expression: (?<=[\[\|])[^\[]*?\|:

import re

s = "something [[remove|keep]] something [[keep]] something [[remove|remove|keep]] something"
print(re.sub("(?<=[\[\|])[^\[]*?\|", "", s))

Output:

something [[keep]] something [[keep]] something [[keep]] something

The regular expression (?<=[\[\|])[^\[]*?\| can be broken down into three parts to return substrings that…

  • (?<=[\[\|]) – begins with either [ or |
  • [^\[]*? – contains anything (non-greedy) that is not a [
  • \| – and ends with |
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