在Go中拆分字符串并保留转义空格。

huangapple go评论88阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年6月17日 13:37:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/72654752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定