Reputation: 110103
I have the following string:
"Person One (Something inside here) Second Thing (another thing) OK (something else)"
I need to get the following:
"Something inside here (Person One) another thing (Second Thing) something else (OK)"
Currently I am doing it like:
inside_parens = []
for item in str.split("("):
if not ")" in item:
inside_parens.append(item)
else:
inside_parens.append(item.split("(")[0])
...
What would be a better approach?
Upvotes: 2
Views: 271
Reputation: 90742
>>> s = 'Person One (Something inside here) Second Thing (another thing) OK (something else)'
>>> import re
>>> re.sub('(.*?) \((.*?)\)( ?)', r'\2 (\1)\3', s)
'Something inside here (Person One) another thing (Second Thing) something else (OK)'
The way in which whitespace needs to be not switched around makes it a tad uglier, but it's not a very bad regular expression.
Upvotes: 7