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

通过正则表达式从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).
    点赞 评论

相关推荐 更多相似问题