Skip to content

Instantly share code, notes, and snippets.

@PaluMacil
Created October 6, 2016 03:52
Show Gist options
  • Save PaluMacil/15b688cc0ff155907d7204c880e4f0af to your computer and use it in GitHub Desktop.
Save PaluMacil/15b688cc0ff155907d7204c880e4f0af to your computer and use it in GitHub Desktop.
parse args from a string by splitting on spaces, leaving quoted strings together as one arg
package main
import (
"fmt"
)
func parse(line string) ([]string, error) {
args := []string{}
quoted := false
newArg := []rune{}
for i, r := range line {
s := string(r)
if s == ` ` && quoted == false {
args = append(args, string(newArg))
newArg = newArg[:0]
} else {
if s == `"` {
quoted = !quoted
}
newArg = append(newArg, r)
if i+1 == len(line) {
args = append(args, string(newArg))
}
}
}
return args, nil
}
func main() {
p1, _ := parse(`gdfs sgfd saf "sdf dfg"`)
p2, _ := parse(`gdfs sgfd "sdf dfg" saf`)
p3, _ := parse(`"sdf dfg" gdfs sgfd saf`)
fmt.Println(p1)
fmt.Println(p2)
fmt.Println(p3)
}
@PaluMacil
Copy link
Author

Anyone may use this with or without attribution. I am placing it under public domain. If your jurisdiction does not recognize public domain, consider it to be under a standard MIT license.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment