swapping the content inside and outside of the brackets with regular expression

I would like to swap the content of inside and outside of the brackets

some outside text (some inside text) some other outside text (some inside text) 

I tried:

text="some outside text (some inside text) some other outside text (some inside text)" p=re.compile('(?P<before>.*?)\((?P<innertext>.*?)\)(?P<after>.*)') print(p.sub("(\g<before>)\g<innertext>(\g<after>)",text)) 

but it only applies to the first match

>>>(some outside text )some inside text( some other outside text (some inside text)) 
Add Comment
2 Answer(s)

your regex is just a bit too complicated. drop the ‘after’ group and things should work fine

import re  text = """\ some outside text (some inside text) some other outside text (some inside text)\ again (some text) outside outside outside (inside here) bla bla\ """  print(re.sub(r"(?P<before>.*?)\((?P<innertext>.*?)\)", "(\g<before>)\g<innertext>", text)) 

prints

(some outside text )some inside text( some other outside text )some inside text(again )some text( outside outside outside )inside here bla bla 
Add Comment

All that you have to do is remove the "after" part from your regexp to ensure that the regexp only matches the part that you are interested in replacing with each match, and then there will be multiple matches replaced. By including the "after" part in your regexp, the whole string is matched on the first match, and nothing more happens after that.

text = "some outside text (some inside text) some other outside text (some inside text)" p = re.compile('(?P<before>.*?)\((?P<innertext>.*?)\)') print(p.sub("(\g<before>)\g<innertext>",text)) 

gives

(some outside text )some inside text( some other outside text )some inside text 

Though you might also want to handle the whitespace slightly differently:

>>> p = re.compile('\s*(?P<before>.*?)\s*\((?P<innertext>.*?)\)') >>> p.sub("(\g<before>) \g<innertext> ",text).strip() '(some outside text) some inside text (some other outside text) some inside text' 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.