【问题标题】:Remove quotes between letters删除字母之间的引号
【发布时间】:2017-06-05 19:43:08
【问题描述】:

在 golang 中,如何删除两个字母之间的引号,如下所示:

import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}

功能:

import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}

例如:

"bus"zipcode" = "bus 邮编"

【问题讨论】:

  • 问题是引号是成对的,并且在字母之间没有任何关系,除非字母是引号的分隔符。即使这样也没有实际意义,因为在 aadsfsdf""""asdf 中,没有任何变化。

标签: regex string go quotes


【解决方案1】:

您可以使用一个简单的\b"\b 正则表达式,它仅在 前面带有单词边界时匹配双引号:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var a = "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}

func RemoveQuotes(s string) string {
    re := regexp.MustCompile(`\b"\b`)
    return re.ReplaceAllString(s, "")
}

查看Go demo 打印"test1","test2","test3"

另外,请参阅online regex demo

【讨论】:

    【解决方案2】:

    当您评论 I want to only quote inside test3 时,我不确定您需要什么。

    此代码与您一样从内部删除引号,但它使用fmt.Sprintf() 添加引号

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        var a = "\"test1\",\"test2\",\"tes\"t3\""
        fmt.Println(RemoveQuotes(a))
    }
    
    func RemoveQuotes(s string) string {
        s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters
    
        return fmt.Sprintf(`"%s"`, s)
    }
    

    https://play.golang.org/p/dKB9DwYXZp

    【讨论】:

    • 感谢@Gerep 的回答。但是您的代码重新编写了“test1,test2,test3”,我想“test1”,“test2”,“test3”。
    【解决方案3】:

    在您的示例中,您定义了一个字符串变量,因此外部引号不是实际字符串的一部分。如果您要执行fmt.Println("bus\"zipcode"),屏幕上的输出将是bus"zipcode。如果您的目标是用空格替换字符串中的引号,那么您需要将引号替换为空字符串,而不是空格 - s = strings.Replace(s, "\"", " ", -1)。虽然如果您想完全删除引号,您可以执行以下操作:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func RemoveQuotes(s string) string {
        result := ""
        arr := strings.Split(s, ",")
        for i:=0;i<len(arr);i++ {
           sub := strings.Replace(arr[i], "\"", "", -1)
           result = fmt.Sprintf("%s,\"%s\"", result, sub)
        }
    
        return result[1:]
    }
    
    func main() {
        a:= "\"test1\",\"test2\",\"tes\"t3\""
        fmt.Println(RemoveQuotes(a))
    }
    

    但是请注意,这不是很有效,但我认为在这种情况下更多的是学习如何做到这一点。

    【讨论】:

    • var a 是一个不好的例子。我的 var a = "\"test1\",\"test2\",\"tes\"t3\""。我只想在 test3 内引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多