删除字母之间的引号

时间:2017-06-05 19:43:08

标签: regex string go quotes

在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“

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

在您的示例中,您定义了一个字符串变量,因此外部引号不是实际字符串的一部分。如果您执行hex = uint8(hex2dec('1B')); temp = typecast(uint8(hex2dec('AA')), 'int8'); disp(temp); temp = bitshift(temp,-7); disp(temp); temp = bitand(typecast(temp,'uint8'),hex); disp(temp); galois_value = bitxor(bitshift(uint16(hex2dec('AA')),1),uint16(temp)); disp(galois_value); ,屏幕上的输出将为fmt.Println("bus\"zipcode")。如果您的目标是用空格替换字符串中的引号,那么您需要像使用空格一样替换引号,而不是空格 - bus"zipcode。虽然如果你想完全删除引号,你可以这样做:

s = strings.Replace(s, "\"", " ", -1)

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

答案 2 :(得分:0)

评论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

相关问题