From 073f231b890cb0abd43a00e3dda5c435bbb4d614 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Mon, 10 Feb 2025 21:35:51 -0500 Subject: [PATCH] Added function and examples for ReplaceAllFunc() --- regex/example_test.go | 11 ++++++++++- regex/matching.go | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/regex/example_test.go b/regex/example_test.go index 94b4998..9438cd9 100644 --- a/regex/example_test.go +++ b/regex/example_test.go @@ -2,6 +2,7 @@ package regex_test import ( "fmt" + "strings" "gitea.twomorecents.org/Rockingcool/kleingrep/regex" ) @@ -167,6 +168,14 @@ 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`)) + fmt.Println(regexComp.ReplaceAllLiteral(inputStr, `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 +} diff --git a/regex/matching.go b/regex/matching.go index 80c5cc6..a344a40 100644 --- a/regex/matching.go +++ b/regex/matching.go @@ -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 + +}