You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式将URL路径中的{xxx}转为:xxx格式?

用正则表达式转换URL路径格式

当然可以用正则表达式完成这个转换,核心思路就是匹配{xxx}格式的片段,把它替换成:xxx。

具体实现示例

JavaScript 版本

const originalPath = '/api/accounts/{account_id}/buy/{id}';
const transformedPath = originalPath.replace(/\{([^}]+)\}/g, ':$1');
console.log(transformedPath); // 输出: /api/accounts/:account_id/buy/:id

Python 版本

import re
original_path = '/api/accounts/{account_id}/buy/{id}'
transformed_path = re.sub(r'\{([^}]+)\}', r':\1', original_path)
print(transformed_path) # 输出: /api/accounts/:account_id/buy/:id

正则规则说明

  • \{([^}]+)\}:
    • \{ 匹配路径里的左大括号{
    • ([^}]+) 捕获大括号内的变量名(匹配任意非右大括号的字符,至少一个)
    • \} 匹配路径里的右大括号}
  • 全局标志g(JavaScript)确保替换所有符合规则的片段,Python的re.sub默认会替换所有匹配项
  • 替换内容:$1(或:\\1)里的$1(\\1)代表捕获到的变量名,直接拼接成:变量名的格式

内容的提问来源于stack exchange,提问作者Ming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:25:00