| 1 |
package chart |
| 2 |
|
| 3 |
import "strings" |
| 4 |
|
| 5 |
|
| 6 |
func SplitCSV(text string) (output []string) { |
| 7 |
if len(text) == 0 { |
| 8 |
return |
| 9 |
} |
| 10 |
|
| 11 |
var state int |
| 12 |
var word []rune |
| 13 |
var opened rune |
| 14 |
for _, r := range text { |
| 15 |
switch state { |
| 16 |
case 0: |
| 17 |
if isQuote(r) { |
| 18 |
opened = r |
| 19 |
state = 1 |
| 20 |
} else if isCSVDelim(r) { |
| 21 |
output = append(output, strings.TrimSpace(string(word))) |
| 22 |
word = nil |
| 23 |
} else { |
| 24 |
word = append(word, r) |
| 25 |
} |
| 26 |
case 1: |
| 27 |
if matchesQuote(opened, r) { |
| 28 |
state = 0 |
| 29 |
continue |
| 30 |
} |
| 31 |
word = append(word, r) |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
if len(word) > 0 { |
| 36 |
output = append(output, strings.TrimSpace(string(word))) |
| 37 |
} |
| 38 |
return |
| 39 |
} |
| 40 |
|
| 41 |
func isCSVDelim(r rune) bool { |
| 42 |
return r == rune(',') |
| 43 |
} |
| 44 |
|
| 45 |
func isQuote(r rune) bool { |
| 46 |
return r == '"' || r == '\'' || r == '“' || r == '”' || r == '`' |
| 47 |
} |
| 48 |
|
| 49 |
func matchesQuote(a, b rune) bool { |
| 50 |
if a == '“' && b == '”' { |
| 51 |
return true |
| 52 |
} |
| 53 |
if a == '”' && b == '“' { |
| 54 |
return true |
| 55 |
} |
| 56 |
return a == b |
| 57 |
} |