From 1746ee10a61a7ca21dd7f0dd646af273a84d7b44 Mon Sep 17 00:00:00 2001 From: GoEdgeLab Date: Sat, 18 Mar 2023 11:10:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=86=E9=9A=94=E5=85=B3?= =?UTF-8?q?=E9=94=AE=E8=AF=8D=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/utils/strings.go | 51 ++++++++++++++++++++++++++++++++++ internal/utils/strings_test.go | 28 +++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/internal/utils/strings.go b/internal/utils/strings.go index c71793aa..03ceb681 100644 --- a/internal/utils/strings.go +++ b/internal/utils/strings.go @@ -82,3 +82,54 @@ func LimitString(s string, maxLength int) string { } 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 +} diff --git a/internal/utils/strings_test.go b/internal/utils/strings_test.go index 796c9ce0..90248ec6 100644 --- a/internal/utils/strings_test.go +++ b/internal/utils/strings_test.go @@ -40,3 +40,31 @@ func TestLimitString(t *testing.T) { a.IsTrue(utils.LimitString("中文测试", 1) == "") 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)) + } +} \ No newline at end of file