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

求适配两种URL场景的正则表达式,提取customerid与branchid

用单个正则表达式从URL中提取customerid和branchid

问题背景

需要从URL中提取customerid和branchid,其中branchid始终紧跟在/branches之后,但它可能出现在URL末尾,也可能后面还有其他路径片段。

示例URL:

http://localhost:8080/customer-api/customers/1128952/branches/83370
http://localhost:8080/customer-api/customers/1128952/branches/83370/validate

其中1128952是customerid,83370是branchid。

目前已有两个正则分别对应单一场景:

  • 匹配URL末尾为branchid的情况:
    ^.*customers/(.*?)/branches/(.*?)$ 
    
  • 匹配branchid后还有后续路径的情况:
    ^.*customers/(.*?)/branches/(.*?)/.*$
    

需要一个能同时覆盖两种场景的通用正则表达式。

解决方案

使用以下正则即可兼容两种场景:

^.*customers/(.*?)/branches/(.*?)(?:/.*)?$

正则说明

  • ^.*customers/:匹配URL开头到customers/的所有内容
  • (.*?):第一个捕获组,提取customers/后到下一个/之间的customerid(非贪婪匹配避免误取多余内容)
  • /branches/:匹配固定路径片段/branches/
  • (.*?):第二个捕获组,提取branches/后的branchid,非贪婪匹配确保只取到下一个/之前的内容(有后续路径时)或URL末尾(无后续路径时)
  • (?:/.*)?:非捕获组,匹配可选的后续路径部分,?标记该部分可存在也可不存在,完美兼容两种场景
  • $:匹配URL结尾

验证结果

  • 对第一个示例URL,捕获组1得到1128952,捕获组2得到83370
  • 对第二个示例URL,捕获组1得到1128952,捕获组2得到83370

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:08:16