删除字母之间的引号

Remove quotes between letters

在 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 zipcode"

在您的示例中,您定义了一个字符串变量,因此外引号不是实际字符串的一部分。如果您执行 fmt.Println("bus\"zipcode"),屏幕上的输出将是 bus"zipcode。如果您的目标是用 space 替换字符串中的引号,那么您需要用 space - 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))
}

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

我不确定你在评论时需要什么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

您可以使用一个简单的 \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