Wrote function and example for ReplaceAllLiteral()

implementBackreferences
Aadhavan Srinivasan 4 weeks ago
parent 668df8b70a
commit 3b7257c921

@ -162,3 +162,11 @@ func ExampleReg_ReplaceAll() {
fmt.Println(regexComp.ReplaceAll(inputStr, `$2$1`)) fmt.Println(regexComp.ReplaceAll(inputStr, `$2$1`))
// Output: d5t9 // Output: d5t9
} }
func ExampleReg_ReplaceAllLiteral() {
regexStr := `fox|dog`
inputStr := "the quick brown fox jumped over the lazy dog"
regexComp := regex.MustCompile(regexStr)
fmt.Println(regexComp.ReplaceAll(inputStr, `duck`))
// Output: the quick brown duck jumped over the lazy duck
}

@ -404,7 +404,7 @@ func (re Reg) ReplaceAll(src string, repl string) string {
currentMatch := 0 currentMatch := 0
dst := "" dst := ""
for i < len(src) { for i < len(src) {
if currentMatch <= len(matches) && matches[currentMatch][0].IsValid() && i == matches[currentMatch][0].StartIdx { if currentMatch < len(matches) && matches[currentMatch][0].IsValid() && i == matches[currentMatch][0].StartIdx {
dst += re.Expand("", repl, src, matches[currentMatch]) dst += re.Expand("", repl, src, matches[currentMatch])
i = matches[currentMatch][0].EndIdx i = matches[currentMatch][0].EndIdx
currentMatch++ currentMatch++
@ -415,3 +415,23 @@ func (re Reg) ReplaceAll(src string, repl string) string {
} }
return dst return dst
} }
// ReplaceAllLiteral replaces all matches of the expression in src, with the text in repl. The text is replaced directly,
// without any expansion.
func (re Reg) ReplaceAllLiteral(src string, repl string) string {
zerogroups := re.FindAll(src)
currentMatch := 0
i := 0
dst := ""
for i < len(src) {
if currentMatch < len(zerogroups) && i == zerogroups[currentMatch].StartIdx {
dst += repl
i = zerogroups[currentMatch].EndIdx
} else {
dst += string(src[i])
i++
}
}
return dst
}

Loading…
Cancel
Save