github.com/psexton/git-lfs@v2.1.1-0.20170517224304-289a18b2bc53+incompatible/tools/str_tools.go (about) 1 package tools 2 3 import "regexp" 4 5 var ( 6 // quoteFieldRe greedily matches between matching pairs of '', "", or 7 // non-word characters. 8 quoteFieldRe = regexp.MustCompile("'(.*)'|\"(.*)\"|(\\S*)") 9 ) 10 11 // QuotedFields is an alternative to strings.Fields (see: 12 // https://golang.org/pkg/strings#Fields) that respects spaces between matching 13 // pairs of quotation delimeters. 14 // 15 // For instance, the quoted fields of the string "foo bar 'baz etc'" would be: 16 // []string{"foo", "bar", "baz etc"} 17 // 18 // Whereas the same argument given to strings.Fields, would return: 19 // []string{"foo", "bar", "'baz", "etc'"} 20 func QuotedFields(s string) []string { 21 submatches := quoteFieldRe.FindAllStringSubmatch(s, -1) 22 out := make([]string, 0, len(submatches)) 23 24 for _, matches := range submatches { 25 // if a leading or trailing space is found, ignore that 26 if matches[0] == "" { 27 continue 28 } 29 30 // otherwise, find the first non-empty match (inside balanced 31 // quotes, or a space-delimited string) 32 var str string 33 for _, m := range matches[1:] { 34 if len(m) > 0 { 35 str = m 36 break 37 } 38 } 39 40 out = append(out, str) 41 } 42 43 return out 44 }