我有一个字符串变量:如何获得os.Args般的记号在命令行字符串
commandLineString := `echo -n "a b c d"`
我想将它隐蔽于:
args := []string{"echo", "-n", "\"a b c d\""}
我该怎么办它?
我有一个字符串变量:如何获得os.Args般的记号在命令行字符串
commandLineString := `echo -n "a b c d"`
我想将它隐蔽于:
args := []string{"echo", "-n", "\"a b c d\""}
我该怎么办它?
如果字符串修复了3个参数,您可以通过strings.SplitN
来完成。这里是关于golang字符串库的完整文档。 https://golang.org/pkg/strings/#SplitN
CMIIW ^^
这可以在一个非常紧凑的方式使用regular expression表示。
输入(命令)是一系列的标记:
和:
从上市标准的正则表达式:
("[^"]*"|[^"\s]+)(\s+|$)
Criteria: __2____ __1___ __3__
使用Go的regexp
包的解决方案是很短:
s := `echo -n "a b c d"`
pattern := `("[^"]*"|[^"\s]+)(\s+|$)`
r := regexp.MustCompile(pattern)
fmt.Printf("%q\n", r.FindAllStringSubmatch(s, -1))
fmt.Printf("%q\n", r.FindAllString(s, -1))
输出(尝试在Go Playground):
[["echo " "echo" " "] ["-n " "-n" " "] ["\"a b c d\"" "\"a b c d\"" ""]]
["echo " "-n " "\"a b c d\""]
备注是的regexp.FindAllString()
结果还包含标记之间的定界符(空格),所以你可以调用strings.TrimSpace()
他们删除这些:
ss := r.FindAllString(s, -1)
out1 := make([]string, len(ss))
for i, v := range ss {
out1[i] = strings.TrimSpace(v)
}
fmt.Printf("%q\n", out1)
这给所需的输出:
["echo" "-n" "\"a b c d\""]
或者,你可以使用的regexp.FindAllStringSubmatch()
结果:它返回切片的切片,使用第二元件(位于索引1
)从每个元素:
sss := r.FindAllStringSubmatch(s, -1)
out2 := make([]string, len(sss))
for i, v := range sss {
out2[i] = v[1]
}
fmt.Printf("%q\n", out2)
这也给了所需的输出:
["echo" "-n" "\"a b c d\""]
尝试这些在Go Playground)。
https://www.google.co.id/#q=golang+split+string+by+space+keep+quoted+string – har07
具体而言,[此主题](https://groups.google.com /论坛/#!主题/ golang-nuts/pNwqLyfl2co),它使用库[go-shellwords](https://github.com/mattn/go-shellwords)提出了几种方法之一。 – har07
@ har07它适用于我所需要的,谢谢你许多! –