Split a string in space, except for internal quotation marks - Go

I was wondering if it is possible in any way to easily split a string into spaces, except when the space inside the quotation marks?

For example, change

Foo bar random "letters lol" stuff

at

Foo, bar, randomAnd"letters lol" stuff

+4
source share
3 answers

Think about it. You have a string in comma-delimited file (CSV) format , RFC4180 , except that your separator, pairs outside of quotation marks, is space (instead of a comma). For instance,

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)
    }
}

Playground: https://play.golang.org/p/Ed4IV97L7H

Conclusion:

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

Fields:
"Foo"
"bar"
"random"
"letters lol"
"stuff"
+7
source

Try this :

package main

import (
    "fmt"
    "strings"
    "text/scanner"
)

func main() {
    var s scanner.Scanner
    s.Init(strings.NewReader(src))
    slice := make([]string, 0, 5)
    for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
        slice = append(slice, s.TokenText())
    }
    out := strings.Join(slice, ", ")
    fmt.Println(out)
}

const src = `Foo bar random "letters lol" stuff`

output:

Foo, bar, random, "letters lol", stuff
+1

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"]

If you want to know more about regex, here is a great SO answer with super handy resources at the end - Regular Expression Learning

Hope this helps

0
source

Source: https://habr.com/ru/post/1689830/


All Articles