简体   繁体   中英

How to get os.Args-like tokens from a command line string

I have a string variable:

commandLineString := `echo -n "a b c d"`

I want to covert it to:

args := []string{"echo", "-n", "\\"abcd\\""}

How can I do it?

This can be expressed using regular expression in a very compact way.

The input (command) is a series of tokens that are:

  1. either non-quoted and cannot contain quotes and spaces,
  2. or quoted and spawn until the next quotation mark and can contain spaces (but not quotation mark).

And:

  1. Tokens are separated by spaces, or the end of input.

The regular expression from the listed criteria:

           ("[^"]*"|[^"\s]+)(\s+|$)

Criteria:   __2____ __1___   __3__

Using Go's regexp package the solution is quite short:

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))

Output (try it on the Go Playground ):

[["echo " "echo" " "] ["-n " "-n" " "] ["\"a b c d\"" "\"a b c d\"" ""]]
["echo " "-n " "\"a b c d\""]

Note that the result of regexp.FindAllString() also contains the delimeters (spaces) between tokens, so you may call strings.TrimSpace() on them to remove those:

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)

Which gives the desired output:

["echo" "-n" "\"a b c d\""]

Or you may use the result of regexp.FindAllStringSubmatch() : it returns a slice of slices, use the 2nd element (at index 1 ) from each element:

sss := r.FindAllStringSubmatch(s, -1)
out2 := make([]string, len(sss))
for i, v := range sss {
    out2[i] = v[1]
}
fmt.Printf("%q\n", out2)

Which also gives the desired output:

["echo" "-n" "\"a b c d\""]

Try these on the Go Playground ).

If the string are fix have 3 parameters you can do by strings.SplitN . here are the full documentation about strings library of golang. https://golang.org/pkg/strings/#SplitN

CMIIW ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM