使用 Go 解析字符串,如命令行参数
Parse strings like command line arguments with Go
如何获取一个字符串并将其当作一系列命令行参数来解析?我希望能够获取一个字符串并使用标志 and/or pflag 对其进行解析。我该怎么做?
package main
import (
"fmt"
"os"
flag "github.com/spf13/pflag"
)
func main() {
command := `unimportant -fb "quoted string"`
var (
foo bool
bar string
)
flag.BoolVarP(&foo, "foo", "f", false, "foo")
flag.StringVarP(&bar, "bar", "b", "default", "bar")
// Parse command
os.Args = append(os.Args, "-fb", "quoted string")
flag.Parse()
fmt.Println(command)
fmt.Println("foo", foo)
fmt.Println("bar", bar)
}
正则表达式可用于检测每个参数。参数有两种可能的形式:
- 一组字母和一个负号:
[-a-zA-Z]+
- 夹在两个中间的东西":
".*?"
关于 regexp
包的信息:https://pkg.go.dev/regexp
关于 regexp
语法的信息:https://pkg.go.dev/regexp/syntax@go1.17.6
re := regexp.MustCompile(`([-a-zA-Z]+)|(".*?[^\]")|("")`)
command := `unimportant -fb "quoted string"`
allArgs := re.FindAllString(command, -1)
//fmt.Printf("%+v\n", allArgs)
// to remove "
for _, arg := range allArgs {
if arg[0] == '"' {
arg = arg[1 : len(arg)-1]
}
fmt.Println(arg)
}
输出:
unimportant
-fb
quoted string
最简单的方法是使用包 shellwords
to parse your string into an argv
of shell words, and then use a command-line parser other than flag
or pflag
that supports parsing an arbitrary argv
(say flags
,但有很多可供选择。)
// Parse your string into an []string as the shell would.
argv, err := shellwords.Parse("./foo --bar=baz")
// argv should be ["./foo", "--bar=baz"]
...
// define your options, etc. here
...
extraArgs, err := flags.ParseArgs(&opts, argv)
如何获取一个字符串并将其当作一系列命令行参数来解析?我希望能够获取一个字符串并使用标志 and/or pflag 对其进行解析。我该怎么做?
package main
import (
"fmt"
"os"
flag "github.com/spf13/pflag"
)
func main() {
command := `unimportant -fb "quoted string"`
var (
foo bool
bar string
)
flag.BoolVarP(&foo, "foo", "f", false, "foo")
flag.StringVarP(&bar, "bar", "b", "default", "bar")
// Parse command
os.Args = append(os.Args, "-fb", "quoted string")
flag.Parse()
fmt.Println(command)
fmt.Println("foo", foo)
fmt.Println("bar", bar)
}
正则表达式可用于检测每个参数。参数有两种可能的形式:
- 一组字母和一个负号:
[-a-zA-Z]+
- 夹在两个中间的东西":
".*?"
关于 regexp
包的信息:https://pkg.go.dev/regexp
关于 regexp
语法的信息:https://pkg.go.dev/regexp/syntax@go1.17.6
re := regexp.MustCompile(`([-a-zA-Z]+)|(".*?[^\]")|("")`)
command := `unimportant -fb "quoted string"`
allArgs := re.FindAllString(command, -1)
//fmt.Printf("%+v\n", allArgs)
// to remove "
for _, arg := range allArgs {
if arg[0] == '"' {
arg = arg[1 : len(arg)-1]
}
fmt.Println(arg)
}
输出:
unimportant
-fb
quoted string
最简单的方法是使用包 shellwords
to parse your string into an argv
of shell words, and then use a command-line parser other than flag
or pflag
that supports parsing an arbitrary argv
(say flags
,但有很多可供选择。)
// Parse your string into an []string as the shell would.
argv, err := shellwords.Parse("./foo --bar=baz")
// argv should be ["./foo", "--bar=baz"]
...
// define your options, etc. here
...
extraArgs, err := flags.ParseArgs(&opts, argv)