Added function and examples for ReplaceAllFunc()

implementBackreferences v0.2.0
Aadhavan Srinivasan 4 weeks ago
parent 3b7257c921
commit 073f231b89

@ -2,6 +2,7 @@ package regex_test
import ( import (
"fmt" "fmt"
"strings"
"gitea.twomorecents.org/Rockingcool/kleingrep/regex" "gitea.twomorecents.org/Rockingcool/kleingrep/regex"
) )
@ -167,6 +168,14 @@ func ExampleReg_ReplaceAllLiteral() {
regexStr := `fox|dog` regexStr := `fox|dog`
inputStr := "the quick brown fox jumped over the lazy dog" inputStr := "the quick brown fox jumped over the lazy dog"
regexComp := regex.MustCompile(regexStr) regexComp := regex.MustCompile(regexStr)
fmt.Println(regexComp.ReplaceAll(inputStr, `duck`)) fmt.Println(regexComp.ReplaceAllLiteral(inputStr, `duck`))
// Output: the quick brown duck jumped over the lazy duck // Output: the quick brown duck jumped over the lazy duck
} }
func ExampleReg_ReplaceAllFunc() {
regexStr := `\w{5,}`
inputStr := `all five or more letter words in this string are capitalized`
regexComp := regex.MustCompile(regexStr)
fmt.Println(regexComp.ReplaceAllFunc(inputStr, strings.ToUpper))
// Output: all five or more LETTER WORDS in this STRING are CAPITALIZED
}

@ -428,6 +428,7 @@ func (re Reg) ReplaceAllLiteral(src string, repl string) string {
if currentMatch < len(zerogroups) && i == zerogroups[currentMatch].StartIdx { if currentMatch < len(zerogroups) && i == zerogroups[currentMatch].StartIdx {
dst += repl dst += repl
i = zerogroups[currentMatch].EndIdx i = zerogroups[currentMatch].EndIdx
currentMatch += 1
} else { } else {
dst += string(src[i]) dst += string(src[i])
i++ i++
@ -435,3 +436,25 @@ func (re Reg) ReplaceAllLiteral(src string, repl string) string {
} }
return dst 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
}

Loading…
Cancel
Save