如何在Golang中去除字符串周围的引号

huangapple go评论107阅读模式
英文:

How to remove quotes from around a string in Golang

问题

我在Golang中有一个被引号包围的字符串。我的目标是去除两侧的所有引号,但忽略字符串内部的引号。我应该如何做到这一点?我的直觉告诉我可以使用类似C#中的RemoveAt函数,但我在Go中没有找到类似的函数。

例如:

"hello""world"

应该转换为:

hello""world

为了进一步澄清,这个:

"""hello"""

将变成这样:

""hello""

因为只有外部的引号应该被移除。

英文:

I have a string in Golang that is surrounded by quote marks. My goal is to remove all quote marks on the sides, but to ignore all quote marks in the interior of the string. How should I go about doing this? My instinct tells me to use a RemoveAt function like in C#, but I don't see anything like that in Go.

For instance:

"hello""world"

should be converted to:

hello""world

For further clarification, this:

"""hello"""

would become this:

""hello""

because the outer ones should be removed ONLY.

答案1

得分: 40

使用切片表达式:

s = s[1 : len(s)-1]

如果有可能引号不存在,则使用以下代码:

if len(s) > 0 && s[0] == '"' {
    s = s[1:]
}
if len(s) > 0 && s[len(s)-1] == '"' {
    s = s[:len(s)-1]
}

playground 示例

英文:

Use a slice expression:

s = s[1 : len(s)-1]

If there's a possibility that the quotes are not present, then use this:

if len(s) > 0 && s[0] == '"' {
	s = s[1:]
}
if len(s) > 0 && s[len(s)-1] == '"' {
	s = s[:len(s)-1]
}

playground example

答案2

得分: 13

strings.Trim()函数可以用于删除字符串的前导和尾随空格。如果双引号位于字符串之间,它将无法起作用。

// strings.Trim()将删除左右两侧的所有出现

s := """hello"""
fmt.Println("Before Trim: " + s) // Before Trim: """hello"""
fmt.Println("After Trim: " + strings.Trim(s, ")) // After Trim: hello

// strings.Trim()不会删除实际字符串内部的任何出现

s2 := ""Hello" " " "World""
fmt.Println("\nBefore Trim: " + s2) // Before Trim: ""Hello" " " "World""
fmt.Println("After Trim: " + strings.Trim(s2, ")) // After Trim: Hello" " " "World

Playground链接 - https://go.dev/play/p/yLdrWH-1jCE

英文:

strings.Trim() can be used to remove the leading and trailing whitespace from a string. It won't work if the double quotes are in between the string.

// strings.Trim() will remove all the occurrences from the left and right

s := `"""hello"""`
fmt.Println("Before Trim: " + s)                    // Before Trim: """hello"""
fmt.Println("After Trim: " + strings.Trim(s, "\"")) // After Trim: hello

// strings.Trim() will not remove any occurrences from inside the actual string

s2 := `""Hello" " " "World""`
fmt.Println("\nBefore Trim: " + s2)                  // Before Trim: ""Hello" " " "World""
fmt.Println("After Trim: " + strings.Trim(s2, "\"")) // After Trim: Hello" " " "World

Playground link - https://go.dev/play/p/yLdrWH-1jCE

答案3

得分: 3

使用切片表达式(slice expressions)。您应该编写健壮的代码,以便对不完美的输入提供正确的输出。例如,

package main

import "fmt"

func trimQuotes(s string) string {
    if len(s) >= 2 {
        if s[0] == '"' && s[len(s)-1] == '"' {
            return s[1 : len(s)-1]
        }
    }
    return s
}

func main() {
    tests := []string{
        `"hello""world"`,
        `"""hello"""`,
        `"`,
        `""`,
        `""""`,
        `goodbye"`,
        `"goodbye"`,
        `goodbye"`,
        `good"bye`,
    }

    for _, test := range tests {
        fmt.Printf("`%s` -> `%s`\n", test, trimQuotes(test))
    }
}

输出:

`"hello""world"` -> `hello""world`
`"""hello"""` -> `""hello""`
`"` -> `"`
`""` -> ``
`""""` -> `"`
`goodbye"` -> `goodbye"`
`"goodbye"` -> `goodbye`
`goodbye"` -> `goodbye"`
`good"bye` -> `good"bye`
英文:

Use slice expressions. You should write robust code that provides correct output for imperfect input. For example,

package main

import "fmt"

func trimQuotes(s string) string {
	if len(s) >= 2 {
		if s[0] == '"' && s[len(s)-1] == '"' {
			return s[1 : len(s)-1]
		}
	}
	return s
}

func main() {
	tests := []string{
		`"hello""world"`,
		`"""hello"""`,
		`"`,
		`""`,
		`"""`,
		`goodbye"`,
		`"goodbye"`,
		`goodbye"`,
		`good"bye`,
	}

	for _, test := range tests {
		fmt.Printf("`%s` -> `%s`\n", test, trimQuotes(test))
	}
}

Output:

`"hello""world"` -> `hello""world`
`"""hello"""` -> `""hello""`
`"` -> `"`
`""` -> ``
`"""` -> `"`
`goodbye"` -> `goodbye"`
`"goodbye"` -> `goodbye`
`goodbye"` -> `goodbye"`
`good"bye` -> `good"bye`

答案4

得分: 2

你可以利用切片来删除切片的第一个和最后一个元素。

package main

import "fmt"

func main() {
    str := `"hello""world"`

    if str[0] == '"' {
        str = str[1:]
    }
    if i := len(str)-1; str[i] == '"' {
        str = str[:i]
    }

    fmt.Println(str)
}

由于切片共享底层内存,这不会复制字符串。它只是将 str 切片的起始位置向后移动一个字符,并将结束位置向前移动一个字符。

这就是 各种 bytes.Trim 函数 的工作原理。

英文:

You can take advantage of slices to remove the first and last element of the slice.

package main

import "fmt"

func main() {
    str := `"hello""world"`

    if str[0] == '"' {
        str = str[1:]
    }
    if i := len(str)-1; str[i] == '"' {
        str = str[:i]
    }

    fmt.Println( str )
}

Since a slice shares the underlying memory, this does not copy the string. It just changes the str slice to start one character over, and end one character sooner.

This is how the various bytes.Trim functions work.

答案5

得分: 0

使用正则表达式的一行代码...

quoted = regexp.MustCompile(`^"(.*)"$`).ReplaceAllString(quoted,`$1`)

但它不一定以你期望的方式处理转义引号。

Go Playground

翻译自这里

英文:

A one-liner using regular expressions...

quoted = regexp.MustCompile(`^"(.*)"$`).ReplaceAllString(quoted,`$1`)

But it doesn't necessarily handle escaped quotes they way you might want.

The Go Playground

Translated from here.

huangapple
  • 本文由 发表于 2017年5月28日 07:46:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/44222554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定