Python 匹配路径中的字符串并替换为先前的路径项

标签 python regex uri

假设我有这个路径(字符串类型)

/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/

相关文章:

python - 获取 ctypes 对象的地址

php - 使用 preg_replace 匹配重复的空格

Java构造函数在不同类中的使用

java - 如何将 Uri 值传递给 bundle 值

Python 3.5 多处理池和队列不起作用

python - 使用 ndimage.interpolation.affine_transform 进行矩阵平移

python - 在列表列表中按索引查找最小值/最大值

regex - sed,如何用2行替换一行?

匹配一个不包含单词 'test' 的句子的正则表达式

jsp - URI 在识别 JSTL 标签库中起什么作用?