我认为你需要一个正则函数而不是正则表达式。问题是纯正则表达式无法匹配任意嵌套的递归模式。因此,它们对于赛道匹配的开启者和关闭者没有多大用处。
相反,编写一个函数来传递跟踪 LIFO 堆栈中的开启者的输入字符串(只需附加到常规 python 列表),然后在找到它们时匹配关闭器(弹出最近的相应开启者):
import re
braces = re.compile(r'(\${)|(})')
def substitute(s, **env):
openers = []
pos = 0
while 1:
mo = braces.search(s, pos)
if mo is None:
break
opener, closer = mo.groups()
if opener:
openers.append(mo.start())
pos = mo.end() + 1
continue
start = openers.pop()
end = mo.end()
body = s[start+2 : end-1]
s = s[:start] + env[body] + s[end:]
return s
print substitute('Return to ${home_${path}} for further ${action}',
home_world='earth',
home_state='kansas',
path='state',
action='orders')