Search code examples
pythonregexstring-parsing

Python remove inner brackets and keep outer brackets


I am struggling with Regex, I have read the wiki and played around, but I cant seem to make the right match.

string_before = 'President [Trump] first name is [Donald], so his full name is [[Donald] [Trump]]' 
string_after = 'President [Trump] first name is [Donald], so his full name is [Donald Trump]' 

I want to remove any possible brackets inside the outer brackets while keeping the outer brackets and the text inside.

Could this be solved easy in python without regex?


Solution

  • In the specific case of two adjacent bracketed expressions inside a pair of brackets, you can do

    string = re.sub(r'\[\[([^][]+)\] \[([^][]+)\]\]', r'[\1 \2]', string)
    

    This does not conveniently extend to an arbitrary number of adjacent bracketed expressions, but perhaps it's enough for your needs.