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

59 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
target := []rune(text)
cur := r.node
var paths []*node
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
4 years ago
}
}
return buf.String()
4 years ago
}