Files
go-zero/core/stringx/replacer.go

61 lines
1.1 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package stringx
import (
"strings"
)
2020-07-26 17:09:05 +08:00
type (
// Replacer interface wraps the Replace method.
2020-07-26 17:09:05 +08:00
Replacer interface {
Replace(text string) string
}
replacer struct {
*node
2020-07-26 17:09:05 +08:00
mapping map[string]string
}
)
// NewReplacer returns a Replacer.
2020-07-26 17:09:05 +08:00
func NewReplacer(mapping map[string]string) Replacer {
2021-04-15 19:49:17 +08:00
rep := &replacer{
node: new(node),
2020-07-26 17:09:05 +08:00
mapping: mapping,
}
for k := range mapping {
rep.add(k)
}
rep.build()
2020-07-26 17:09:05 +08:00
return rep
}
// Replace replaces text with given substitutes.
2020-07-26 17:09:05 +08:00
func (r *replacer) Replace(text string) string {
var buf strings.Builder
2023-02-12 22:20:36 +08:00
var paths []*node
target := []rune(text)
cur := r.node
2023-02-12 22:20:36 +08:00
for len(target) != 0 {
uselessLen, matchLen, nextPaths := cur.longestMatch(target, paths)
if uselessLen > 0 {
buf.WriteString(string(target[:uselessLen]))
target = target[uselessLen:]
}
if matchLen > 0 {
replaced := r.mapping[string(target[:matchLen])]
target = append([]rune(replaced), target[matchLen:]...)
}
if len(nextPaths) != 0 {
cur = nextPaths[len(nextPaths)-1]
paths = nextPaths
} else {
cur = r.node
paths = nil
2020-07-26 17:09:05 +08:00
}
}
2023-02-12 22:20:36 +08:00
return buf.String()
2020-07-26 17:09:05 +08:00
}