通过regexp从url路径中删除特定路径

时间:2018-02-03 21:57:33

标签: regex go

Golang删除特定字符串的方法有很多种。 但是我现在需要使用正则表达式。

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

路径中包含的目标数量可以更改。

1 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式:

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

请参阅regex demo

<强>详情

  • (?:/(?:area1|area2))+ - 出现以下一个或多个序列:
    • / - 一个/字符(无需在Go正则表达式模式中将其转义)
    • (?:area1|area2) - 与area1area2匹配的非捕获组(也可以替换为area[12]或仅area\d+来匹配{{1}和1+位数)
  • area - 第1组:(/|$)或字符串结尾(/将匹配字符串的结尾)。