Util: Support parsing and splitting strings enclosed in quotes in util.SplitString (#85735)

* Support parsing string enclosed in quotation marks in util.SplitString

* Support mixed formats of string list
This commit is contained in:
Misi
2024-04-09 10:35:57 +02:00
committed by GitHub
parent b200156a01
commit 4c12d77b98
3 changed files with 21 additions and 4 deletions

View File

@@ -4,11 +4,14 @@ import (
"encoding/json"
"fmt"
"math"
"regexp"
"strings"
"time"
"unicode"
)
var stringListItemMatcher = regexp.MustCompile(`"[^"]+"|[^,\t\n\v\f\r ]+`)
// StringsFallback2 returns the first of two not empty strings.
func StringsFallback2(val1 string, val2 string) string {
return stringsFallback(val1, val2)
@@ -28,7 +31,8 @@ func stringsFallback(vals ...string) string {
return ""
}
// SplitString splits a string by commas or empty spaces.
// SplitString splits a string and returns a list of strings. It supports JSON list syntax and strings separated by commas or spaces.
// It supports quoted strings with spaces, e.g. "foo bar", "baz".
func SplitString(str string) []string {
if len(str) == 0 {
return []string{}
@@ -44,7 +48,12 @@ func SplitString(str string) []string {
return res
}
return strings.Fields(strings.ReplaceAll(str, ",", " "))
var result []string
matches := stringListItemMatcher.FindAllString(str, -1)
for _, match := range matches {
result = append(result, strings.Trim(match, "\""))
}
return result
}
// GetAgeString returns a string representing certain time from years to minutes.