Search code examples
pythonstringpython-re

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

"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...

    • (?<=[\[\|]) - immediately to the left of the substring is a [ or |
    • [^\[]*? - contains anything (non-greedy) that is not a [
    • \| - and ends with |