2016-12-27 08:35
浏览 1.2k

如何在Go lang中将字符串中的多个斜杠(///)替换为一个斜杠(/)?

Input string: "///hello//stackover.flow"

Expected output: "/hello/stackover.flow"

图片转代码服务由CSDN问答提供 功能建议

输入字符串:“ ///hello//stackover.flow"

预期输出:“ /hello/stackover.flow"

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dpmfur2635 2016-12-27 09:07

    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", "/"))
    打赏 评论
  • dongye9991 2016-12-27 08:45

    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:

    1. Replace multiple slashes with a single slash.
    2. Eliminate each . path name element (the current directory).
    3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
    4. 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 (
    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++ {


    BenchmarkPathRegexp-4        2000000           794 ns/op
    BenchmarkPathClean-4        10000000           145 ns/op
    打赏 评论

相关推荐 更多相似问题