scan for a double quote.extract the part before than and split on spacesscan for the closing double quoteextract this part and append it to the result of the splitreslice the string to be the remainder
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Amazing, I tried to find a package to do this hard work but found nothing, so I have been using regexp: `'.*?'|".*?"|\S+`
Maybe I can use go-shellwords later.
在 2014年7月11日星期五UTC+8上午6时56分14秒,Alex Skinner写道:const NullStr = rune(0)
// ParseArgs will parse a string that contains quoted strings the same as bash does
// (same as most other *nix shells do). This is secure in the sense that it doesn't do any
// executing or interpeting. However, it also doesn't do any escaping, so you shouldn't pass
// these strings to shells without escaping them.
func ParseArgs(str string) ([]string, error) {
var m []string
var s string
str = strings.TrimSpace(str) + " "
lastQuote := NullStr
isSpace := false
for i, c := range str {
switch {
// If we're ending a quote, break out and skip this character
case c == lastQuote:
lastQuote = NullStr
// If we're in a quote, count this character
case lastQuote != NullStr:
s += string(c)
// If we encounter a quote, enter it and skip this character
case unicode.In(c, unicode.Quotation_Mark):
isSpace = false
lastQuote = c
// If it's a space, store the string
case unicode.IsSpace(c):
if 0 == i || isSpace {
continue
}
isSpace = true
m = append(m, s)
s = ""
default:
isSpace = false
s += string(c)
}
}
if lastQuote != NullStr {
return nil, fmt.Errorf("Quotes did not terminate")
}
return m, nil
}
Based on the work of others here I created my own version that passes the tests I needed to pass:* strips outer quotes* keeps inner quotes* empty quotes produce empty string