1 Star 0 Fork 0

h79 / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
regexp.go 2.06 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-10-31 11:43 . bug
package sensitive
import (
"gitee.com/h79/goutils/common/algorithm"
"gitee.com/h79/goutils/common/trie"
"regexp"
"sync"
)
type Regexp struct {
locker sync.Mutex
items map[uint64]*regexp.Regexp
}
func NewRegexp() *Regexp {
return &Regexp{items: make(map[uint64]*regexp.Regexp)}
}
func (r *Regexp) Add(reg string) (*regexp.Regexp, error) {
hashId := algorithm.FnvSum64(reg)
r.locker.Lock()
defer func() {
r.locker.Unlock()
}()
if it, ok := r.items[hashId]; ok {
return it, nil
}
it, err := regexp.Compile(reg)
if err != nil {
return nil, err
}
r.items[hashId] = it
return it, nil
}
func (r *Regexp) Del(reg string) {
hashId := algorithm.FnvSum64(reg)
r.locker.Lock()
defer r.locker.Unlock()
delete(r.items, hashId)
}
func (r *Regexp) Filter(text string) string {
return r.Replace(text, "")
}
func (r *Regexp) Replace(text string, repl string) string {
regs := r.find(text)
if len(regs) <= 0 {
return text
}
for _, reg := range regs {
text = reg.ReplaceAllString(text, repl)
}
return text
}
// FindIn 检测敏感词
func (r *Regexp) FindIn(text string) (bool, string) {
regs := r.find(text)
if len(regs) <= 0 {
return false, ""
}
var in []string
for _, reg := range regs {
in = append(in, reg.FindString(text))
}
return true, in[0]
}
// FindAll 找到所有匹配词
func (r *Regexp) FindAll(text string) []*trie.Group {
r.locker.Lock()
defer r.locker.Unlock()
var (
group []*trie.Group
ff [][]int
)
for _, reg := range r.items {
ff = reg.FindAllStringIndex(text, -1)
if len(ff) <= 0 {
continue
}
for i := range ff {
if len(ff[i]) < 2 {
continue
}
gr := &trie.Group{Text: text[ff[i][0]:ff[i][1]], Index: ff[i][0]}
group = append(group, gr)
}
}
return group
}
func (r *Regexp) Validate(text string) (bool, string) {
validated, first := r.FindIn(text)
return !validated, first
}
func (r *Regexp) find(text string) []*regexp.Regexp {
r.locker.Lock()
defer r.locker.Unlock()
var regs []*regexp.Regexp
for _, v := range r.items {
if v.MatchString(text) {
regs = append(regs, v)
}
}
return regs
}
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.57

搜索帮助