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')
我认为这里需要一个正则函数而不是正则表达式。问题是纯正则表达式不能匹配任意嵌套的递归模式。所以,他们没有太多的使用轨道匹配的开场白和收尾。你知道吗
相反,编写一个函数来传递输入字符串,跟踪后进先出堆栈中的开始符(只需附加到常规python列表中),然后在找到结束符时匹配结束符(弹出最近对应的开始符):
相关问题 更多 >
编程相关推荐