Added function and examples for ReplaceAllFunc()

This commit is contained in:
2025-02-10 21:35:51 -05:00
parent 3b7257c921
commit 073f231b89
2 changed files with 33 additions and 1 deletions

View File

@@ -428,6 +428,7 @@ func (re Reg) ReplaceAllLiteral(src string, repl string) string {
if currentMatch < len(zerogroups) && i == zerogroups[currentMatch].StartIdx {
dst += repl
i = zerogroups[currentMatch].EndIdx
currentMatch += 1
} else {
dst += string(src[i])
i++
@@ -435,3 +436,25 @@ func (re Reg) ReplaceAllLiteral(src string, repl string) string {
}
return dst
}
// ReplaceAllFunc replaces every match of the expression in src, with the return value of the function replFunc.
// replFunc takes in the matched string. The return value is substituted in directly without expasion.
func (re Reg) ReplaceAllFunc(src string, replFunc func(string) string) string {
zerogroups := re.FindAll(src)
currentMatch := 0
i := 0
dst := ""
for i < len(src) {
if currentMatch < len(zerogroups) && i == zerogroups[currentMatch].StartIdx {
dst += replFunc(src[zerogroups[currentMatch].StartIdx:zerogroups[currentMatch].EndIdx])
i = zerogroups[currentMatch].EndIdx
currentMatch += 1
} else {
dst += string(src[i])
i++
}
}
return dst
}