// SplitString split string with a rune comma ignore quoted
func SplitString(str string, r rune) []string {
quoted := false
return strings.FieldsFunc(str, func(r1 rune) bool {
if r1 == '\'' {
quoted = !quoted
}
return !quoted && r1 == r
})
}
// TestSpitString test case
func TestSpitString(t *testing.T) {
str := " arg1 arg2 'hello world' "
arr := SplitString(str, ' ')
fmt.Println(len(arr))
for i, line := range arr {
fmt.Println(i, "---", line)
}
}

在2019年6月3日星期一 UTC+8 11:35:24<Michael Fromberger> 写道:

> You might find http://godoc.org/bitbucket.org/creachadair/shell useful 
> also.
>
> –M
>
>
> On Saturday, June 1, 2019 at 8:14:14 PM UTC-7, AJ ONeal wrote:
>>
>> 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
>>
>> https://play.golang.org/p/NzYUsZ-pm2v 
>>
>> 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
>>> }
>>
>>
>> I may or may not keep this updated at 
>> https://git.coolaj86.com/coolaj86/git-scripts/src/branch/master/git-proxy
>>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/797da957-897c-476d-960a-9c02f5fd6a70n%40googlegroups.com.

Reply via email to