增加分隔关键词函数

This commit is contained in:
GoEdgeLab
2023-03-18 11:10:44 +08:00
parent c84f490645
commit 1746ee10a6
2 changed files with 79 additions and 0 deletions

View File

@@ -82,3 +82,54 @@ func LimitString(s string, maxLength int) string {
} }
return s return s
} }
// SplitKeywordArgs 分隔关键词参数
// 支持hello, "hello", name:hello, name:"hello", name:\"hello\"
func SplitKeywordArgs(s string) (args []splitArg) {
var value []rune
var beginQuote = false
var runes = []rune(s)
for index, r := range runes {
if r == '"' && (index == 0 || runes[index-1] != '\\') {
beginQuote = !beginQuote
continue
}
if !beginQuote && (r == ' ' || r == '\t' || r == '\n' || r == '\r') {
if len(value) > 0 {
args = append(args, parseKeywordValue(string(value)))
value = nil
}
} else {
value = append(value, r)
}
}
if len(value) > 0 {
args = append(args, parseKeywordValue(string(value)))
}
return
}
type splitArg struct {
Key string
Value string
}
func (this *splitArg) String() string {
if len(this.Key) > 0 {
return this.Key + ":" + this.Value
}
return this.Value
}
func parseKeywordValue(value string) (arg splitArg) {
var colonIndex = strings.Index(value, ":")
if colonIndex > 0 {
arg.Key = value[:colonIndex]
arg.Value = value[colonIndex+1:]
} else {
arg.Value = value
}
return
}

View File

@@ -40,3 +40,31 @@ func TestLimitString(t *testing.T) {
a.IsTrue(utils.LimitString("中文测试", 1) == "") a.IsTrue(utils.LimitString("中文测试", 1) == "")
a.IsTrue(utils.LimitString("中文测试", 3) == "中") a.IsTrue(utils.LimitString("中文测试", 3) == "中")
} }
func TestSplitKeywordArgs(t *testing.T) {
{
var keyword = ""
t.Logf("%+v", utils.SplitKeywordArgs(keyword))
}
{
var keyword = "abc"
t.Logf("%+v", utils.SplitKeywordArgs(keyword))
}
{
var keyword = "abc def ghi123"
t.Logf("%+v", utils.SplitKeywordArgs(keyword))
}
{
var keyword = "\"hello world\""
t.Logf("%+v", utils.SplitKeywordArgs(keyword))
}
{
var keyword = "\"hello world\" hello \"world\" \"my name\" call:\"zip name\" slash:\\\"SLASH"
t.Logf("%+v", utils.SplitKeywordArgs(keyword))
}
{
var keyword = "name:abc"
t.Logf("%+v", utils.SplitKeywordArgs(keyword))
}
}