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.
go-zero/core/stringx/replacer.go

62 lines
1.1 KiB
Go

4 years ago
package stringx
import (
"strings"
)
4 years ago
type (
// Replacer interface wraps the Replace method.
4 years ago
Replacer interface {
Replace(text string) string
}
replacer struct {
*node
4 years ago
mapping map[string]string
}
)
// NewReplacer returns a Replacer.
4 years ago
func NewReplacer(mapping map[string]string) Replacer {
rep := &replacer{
node: new(node),
4 years ago
mapping: mapping,
}
for k := range mapping {
rep.add(k)
}
rep.build()
4 years ago
return rep
}
// Replace replaces text with given substitutes.
4 years ago
func (r *replacer) Replace(text string) string {
var buf strings.Builder
var nextStart int
target := []rune(text)
cur := r.node
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
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
4 years ago
}
}
}
return buf.String()
4 years ago
}