Skip to content Skip to sidebar Skip to footer

Python Regex - How To Remove Text Between 2 Characters

How can I remove anything between ')' and '|' For example, str = 'left)garbage|right' I need the output to be 'left)|right'

Solution 1:

>>>import re>>>s = "left)garbage|right">>>re.sub(r'(?<=\)).*?(?=\|)', '', s)
'left)|right'

>>>re.sub(r'\).*?\|', r')|', s)
'left)|right'

Solution 2:

In your specific case, it is

str[:str.index(')')+1] + str[str.index('|'):]

Solution 3:

>>>import re>>>str = 'left)garbage|right'>>>re.sub(r"\).*?\|",")|",str)
'left)|right'

Solution 4:

You can do this:

import re
str = "left)garbage|right"
re.sub(r"(?<=\)).*?(?=\|)", "", str)

Post a Comment for "Python Regex - How To Remove Text Between 2 Characters"