如何用正则表达式将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
相关产品推荐
相关产品推荐

