Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way to delete text between two delimiters

I'm trying to remove wiki formatting from some text so it can be parsed.

What is the most pythonic way to remove two delimiters ('[[' and ']]') all the text between them? The given string will contain multiple occurrences of delimiter pairs.

like image 880
Cheezey Avatar asked Jun 09 '26 06:06

Cheezey


1 Answers

Regular expressions are a good match for your problem.

>>> import re
>>> input_str = 'foo [[bar]] baz [[etc.]]'

If you are wanting to remove the whole [[...]], which is I think what you are asking about,

>>> re.sub(r'\[\[.*?\]\]', '', input_str)
'foo  baz '

If you are wanting to leave the contents of the [[...]] in,

>>> re.sub(r'\[\[(.*?)\]\]', r'\1', input_str)
'foo bar baz etc.'
like image 180
Chris Morgan Avatar answered Jun 11 '26 19:06

Chris Morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!