我有以下字符串:
"Person One (Something inside here) Second Thing (another thing) OK (something else)"
我需要得到以下内容:
"Something inside here (Person One) another thing (Second Thing) something else (OK)"
目前我这样做:
inside_parens = []
for item in str.split("("):
if not ")" in item:
inside_parens.append(item)
else:
inside_parens.append(item.split("(")[0])
...
什么是更好的方法?
答案 0 :(得分:7)
>>> 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)'
白色空间不需要切换的方式使它变得更加丑陋,但这不是一个非常糟糕的正则表达式。