在Space处拆分字符串,除了引号内部 - Go

时间:2017-11-25 19:26:49

标签: string go

我想知道是否有任何方法可以轻松地在空格处拆分字符串,除非空格在引号内?

例如,更改

Foo bar random "letters lol" stuff

Foobarrandom"letters lol" stuff

2 个答案:

答案 0 :(得分:9)

想一想。您有一个逗号分隔值(CSV)文件格式RFC4180的字符串,但您的分隔符,外部引号对是空格(而不是逗号)。例如,

package main

import (
    "encoding/csv"
    "fmt"
    "strings"
)

func main() {
    s := `Foo bar random "letters lol" stuff`
    fmt.Printf("String:\n%q\n", s)

    // Split string
    r := csv.NewReader(strings.NewReader(s))
    r.Comma = ' ' // space
    fields, err := r.Read()
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Printf("\nFields:\n")
    for _, field := range fields {
        fmt.Printf("%q\n", field)
    }
}

游乐场:https://play.golang.org/p/Ed4IV97L7H

输出:

String:
"Foo bar random \"letters lol\" stuff"

Fields:
"Foo"
"bar"
"random"
"letters lol"
"stuff"

答案 1 :(得分:0)

您可以使用regex

这个(go playground)将涵盖引号内多个单词和数组中多个引用条目的所有用例:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := `Foo bar random "letters lol" stuff "also will" work on "multiple quoted stuff"`       
    r := regexp.MustCompile(`[^\s"']+|"([^"]*)"|'([^']*)`) 
    arr := r.FindAllString(s, -1)       
    fmt.Println("your array: ", arr)    
}

输出将是:

[Foo, bar, random, "letters lol", stuff, "also will", work, on, "multiple quoted stuff"]

如果你想了解更多有关正则表达式的信息,请在最后提供超级便利的资源 - Learning Regular Expressions

希望这有帮助