Harry
Harry

Reputation: 1347

remove specific path from url path by regexp

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.

Upvotes: 1

Views: 1089

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

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).

Upvotes: 1

Related Questions