Added function and examples for ReplaceAllFunc()
This commit is contained in:
@@ -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
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user