From 3b7257c92194fa2b796de2bb1cd52c0d3aa3ec7e Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Mon, 10 Feb 2025 21:25:49 -0500 Subject: [PATCH] Wrote function and example for ReplaceAllLiteral() --- regex/example_test.go | 8 ++++++++ regex/matching.go | 22 +++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/regex/example_test.go b/regex/example_test.go index 4f868c6..94b4998 100644 --- a/regex/example_test.go +++ b/regex/example_test.go @@ -162,3 +162,11 @@ func ExampleReg_ReplaceAll() { fmt.Println(regexComp.ReplaceAll(inputStr, `$2$1`)) // 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 +} diff --git a/regex/matching.go b/regex/matching.go index 879585d..80c5cc6 100644 --- a/regex/matching.go +++ b/regex/matching.go @@ -404,7 +404,7 @@ func (re Reg) ReplaceAll(src string, repl string) string { currentMatch := 0 dst := "" 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]) i = matches[currentMatch][0].EndIdx currentMatch++ @@ -415,3 +415,23 @@ func (re Reg) ReplaceAll(src string, repl string) string { } 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 +}