Input string: "///hello//stackover.flow"
Expected output: "/hello/stackover.flow"
Just an option. You can use it if you need to replace some other multiple characters.
re, _ := regexp.Compile("/+")
fmt.Println(re.ReplaceAllLiteralString("///hello//stackover.flow", "/"))
You can use path.Clean
for that.
func Clean(path string) string
Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path. The returned path ends in a slash only if it is the root "/".
If the result of this process is an empty string, Clean returns the string ".".
And here's a simple benchmark which compares it with regexp solution:
package main
import (
"path"
"regexp"
"testing"
)
var p = "///hello//stackover.flow"
func BenchmarkPathRegexp(b *testing.B) {
re := regexp.MustCompile("/+")
for i := 0; i < b.N; i++ {
re.ReplaceAllLiteralString(p, "/")
}
}
func BenchmarkPathClean(b *testing.B) {
for i := 0; i < b.N; i++ {
path.Clean(p)
}
}
Results:
BenchmarkPathRegexp-4 2000000 794 ns/op
BenchmarkPathClean-4 10000000 145 ns/op