假设我有这个路径(字符串类型)
/user/{id}/list/{id}
我想搜索“id”,并且对于每个完全匹配项,我想将 id 替换为紧邻的上一个路径 +“_id”。因此,在上面的示例中,所描述的过程将导致
/user/{user_id}/list/{list_id}
如何在 python 中执行此操作?
编辑:我还想将新的 id 名称存储在变量中,所以我猜该操作不应该到位。
Edit2:路径中可以出现无限数量的 {id}
最佳答案
在替换字符串中使用捕获组和对此捕获的引用:
re.sub(r'([^/]+)/{id}', r'\1/{\1_id}', s)
如果您想将替换内容存储在列表中,您可以这样做:
(python 2.7)
def rep(m):
ids.append('%s_id'%m.group(1))
return '%(g1)s/{%(g1)s_id}'%{'g1':m.group(1)}
ids=[]
re.sub(r'([^/]+)/{id}', rep, s)
(python 3.x)
def rep(m):
ids.append('{}_id'.format(m.group(1)))
return '{0}/{{{0}_id}}'.format(m.group(1))
关于Python 匹配路径中的字符串并替换为先前的路径项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42462424/