go-zero/core/stringx/replacer.go

58 lines
1.0 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
target := []rune(text)
cur := r.node
nextStart := 0
for len(target) != 0 {
used, jump, matched := cur.longestMatch(target, nextStart)
if matched {
replaced := r.mapping[string(target[:used])]
target = append([]rune(replaced), target[used:]...)
cur = r.node
2023-02-04 17:33:47 +08:00
nextStart = 0
} else {
buf.WriteString(string(target[:used]))
target = target[used:]
if jump != nil {
cur = jump
nextStart = jump.depth
} else {
cur = r.node
nextStart = 0
2020-07-26 17:09:05 +08:00
}
}
}
return buf.String()
2020-07-26 17:09:05 +08:00
}