英文:
Split string in Go while preserving escaped spaces
问题
我可以使用strings.Split
函数来拆分字符串:
strings.Split(`Hello World`, " ")
// ["Hello", "World"] (长度为2)
但是我想保留反斜杠转义的空格:
escapePreservingSplit(`Hello\ World`, " ")
// ["Hello\ World"] (长度为1)
在Go中,有什么推荐的方法来实现这个需求?
英文:
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?
答案1
得分: 1
由于Go语言不支持look arounds(正则表达式的一种特性),这个问题并不容易解决。
下面的代码可以接近解决,但会保留尾部的空格:
re := regexp.MustCompile(`.*?[^\\]( |$)`)
split := re.FindAllString(`Hello Cruel\ World Pizza`, -1)
fmt.Printf("%#v", split)
输出结果:
[]string{"Hello ", "Cruel\\ World ", "Pizza"}
然后你可以在后续步骤中修剪所有的字符串。
英文:
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 in a following step.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论