Created
October 6, 2016 03:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.