Home > OS >  Split string in Go while preserving escaped spaces
Split string in Go while preserving escaped spaces

Time:06-18

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?

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related