You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.5 KiB
Go

package cmd
import (
"git.noahlan.cn/northlan/ntools-go/stringn/ac"
"strings"
)
type (
CMD struct {
IsCMD bool // 是否CMD
Arr []string // 具体CMD []string
}
Parser struct {
trie *ac.Trie
allKeyArr []string
keywordMap map[string]struct{}
}
ParserBuilder struct {
}
)
func NewCMDParser(keys []string) *Parser {
p := &Parser{
keywordMap: make(map[string]struct{}),
allKeyArr: make([]string, 0, len(keys)),
}
for _, keyword := range keys {
p.keywordMap[keyword] = struct{}{}
p.allKeyArr = append(p.allKeyArr, keyword)
}
p.trie = ac.NewTrieBuilder().AddStrings(p.allKeyArr).Build()
return p
}
func (p *Parser) ParseTest(content string) {
p.trie.MatchString(content)
}
func (p *Parser) Parse(content string) *CMD {
// 移除多余空格,小写
tmpContent := strings.ToLower(strings.TrimSpace(content))
matches := p.trie.MatchString(tmpContent)
allKeyLen := 0
matchedKeys := make([]string, 0)
for _, match := range matches {
tmp := p.allKeyArr[match.Pattern()]
matchedKeys = append(matchedKeys, tmp)
allKeyLen += len(tmp)
}
isCMD := len(tmpContent) <= allKeyLen
// 避免同类型指令重复
arrMap := make(map[rune]struct{})
var matchedCmdArr []string
if isCMD {
matchedCmdArr = make([]string, 0, len(matchedKeys))
for i := len(matchedKeys) - 1; i >= 0; i-- {
s := matchedKeys[i]
sRune := []rune(s)
if _, ok := arrMap[sRune[0]]; !ok {
arrMap[sRune[0]] = struct{}{}
matchedCmdArr = append(matchedCmdArr, s)
}
}
}
return &CMD{
IsCMD: isCMD,
Arr: matchedCmdArr,
}
}