Python的shlex.split在Go语言中的替代方案

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

python's shlex.split alternative for Go

问题

有没有类似于Python的shlex.split的东西,可以让我简单地解析/拆分/引用/转义类似于shell的引号/反斜杠字符串?

shlex.split是什么:
shlex.split是Python中的一个函数,用于将字符串按照shell语法进行拆分。它可以处理引号、反斜杠和空格等特殊字符。

你可以参考shlex文档了解更多信息:
http://docs.python.org/3.4/library/shlex.html

下面是shlex.split的一个示例:

>>> import shlex
>>> shlex.split('abc ab\ c "ab\"cd" key="\"val\""')
['abc', 'ab c', 'ab"cd', 'key="val"']
英文:

Simple question - is there something like python's shlex.split that would allow me to simply parse/split/quote/escape shell-like quoted/backslashed strings ?

Link to shlex docs:
http://docs.python.org/3.4/library/shlex.html

Example of what shlex.split does:

>>> import shlex
>>> shlex.split('abc ab\\ c  "ab\\"cd" key="\\"val\\""')
['abc', 'ab c', 'ab"cd', 'key="val"']

答案1

得分: 7

标准库中没有提供类似的功能,但是Google发布了他们自己的 shlex 库,该库已经被分叉并在 flynn-archive/go-shlex 中进行了一些更改。

例如:

package main

import (
	"fmt"
	"github.com/google/shlex"
)

func main() {
	input := "abc ab\\ c  \"ab\\\"cd\" key=\"\\\"val\\\"\""
	fmt.Println("Processing:", input)
	tokens, _ := shlex.Split(input)
	fmt.Printf("%#v\n", tokens)
    // []string{"abc", "ab c", "ab\"cd", "key=\"val\""}
}
英文:

Nothing in the standard library, but Google did publish their own shlex library which has been forked and changed some in flynn-archive/go-shlex.

For example:

package main

import (
	"fmt"
	"github.com/google/shlex"
)

func main() {
	input := "abc ab\\ c  \"ab\\\"cd\" key=\"\\\"val\\\"\""
	fmt.Println("Processing:", input)
	tokens, _ := shlex.Split(input)
	fmt.Printf("%#v\n", tokens)
    // []string{"abc", "ab c", "ab\"cd", "key=\"val\""}
}

huangapple
  • 本文由 发表于 2016年5月1日 02:19:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/36958515.html
匿名

发表评论

匿名网友

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

确定