dongqi8030 2018-02-03 21:57
浏览 226
已采纳

通过正则表达式从url路径中删除特定路径

There are many ways to remove specific string by Golang. But I need to use regexp in this time.

func Replace(path, from, to string) string {
    reg, _ := re.Compile(from)
    if reg.MatchString(path) {
        return reg.ReplaceAllString(path, to)
    }
    return "error"
}

//This pattern is OK
fmt.Println(Replace("/nl/amsterdam/area2/area1", `\/+(?:area1|area2).+(/|\z)`, "$1"))
// Output: /nl/amsterdam

//What is wrong??
fmt.Println(Replace("/nl/amsterdam/area2", `\/+(?:area1|area2).+(/|\z)`, "$1"))
// Output: error
// I expect => /nl/amsterdam

fmt.Println(Replace("/nl/amsterdam/area2", `\/+(?:area1|area2)(/|\z)`, "$1"))
// Output: /nl/amsterdam
// This pattern seems OK, but when path is `/nl/amsterdam/area2/area1`, it doesn't work as I expected like the next pattern.

fmt.Println(Replace("/nl/amsterdam/area2/area1", `\/+(?:area1|area2)(/|\z)`, "$1"))
// Output: /nl/amsterdam/area1
// I wanna get /nl/amsterdam

How many targets is included in path is changeable.

  • 写回答

1条回答 默认 最新

  • duanfei8399 2018-02-03 22:51
    关注

    You may use the following regex:

    (?:/(?:area1|area2))+(/|$)
    

    See the regex demo.

    Details

    • (?:/(?:area1|area2))+ - 1 or more occurrences of the following sequence:
      • / - a / char (no need to escape it in the Go regex patterns)
      • (?:area1|area2) - a non-capturing group matching either area1 or area2 (also can be replaced with area[12] or just area\d+ to match area and 1+ digits)
    • (/|$) - Group 1: either / or end of string (\z will match the very end of string).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题