Home > Software design >  Parse strings like command line arguments with Go
Parse strings like command line arguments with Go

Time:02-05

How do I take a string and parse it as if it was a series of command line arguments? I want to be able to take a string and parse that with flag and/or pflag. How do I do this?

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

CodePudding user response:

Regex can use to detect each argument. There are two possible forms for an argument:

  1. a group of letters and a negative sign: [-a-zA-Z]
  2. something sandwiched between two ": ".*?"

Information about regexp package: https://pkg.go.dev/regexp

Information about regexp syntax: https://pkg.go.dev/regexp/[email protected]

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

Output:

unimportant
-fb
quoted string
  •  Tags:  
  • Related