Split string in Go while preserving escaped spaces

Issue

I can split a string with strings.Split:

strings.Split(`Hello World`, " ")
// ["Hello", "World"]  (length 2)

But I’d like to preserve backslash escaped spaces:

escapePreservingSplit(`Hello\ World`, " ")
// ["Hello\ World"] (length 1)

What’s the recommended way to accomplish this in Go?

Solution

Since go does not support look arounds, this problem is not straightforward to solve.

This gets you close, but leaves a the trailing space intact:

re := regexp.MustCompile(`.*?[^\\]( |$)`)
split := re.FindAllString(`Hello Cruel\ World Pizza`, -1)
fmt.Printf("%#v", split)

Output:

[]string{"Hello ", "Cruel\\ World ", "Pizza"}

You could then trim all the strings a following next step.

Answered By – Bohemian

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.