From 50221ff4d9780e1aa4fbb24d608bcad254af7d61 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Mon, 10 Feb 2025 12:29:54 -0500 Subject: [PATCH] Wrote ReplaceAll(), to replace all matches of the regex with a given string --- regex/matching.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/regex/matching.go b/regex/matching.go index faf56a5..879585d 100644 --- a/regex/matching.go +++ b/regex/matching.go @@ -350,7 +350,7 @@ func (re Reg) Expand(dst string, template string, src string, match Match) strin i++ } else { numStr := "" - for unicode.IsDigit(templateRuneSlc[i]) { + for i < len(templateRuneSlc) && unicode.IsDigit(templateRuneSlc[i]) { numStr += string(templateRuneSlc[i]) i++ } @@ -395,3 +395,23 @@ func (re Reg) LiteralPrefix() (prefix string, complete bool) { } return prefix, complete } + +// ReplaceAll replaces all matches of the expression in src, with the text in repl. In repl, variables are interpreted +// as they are in [Reg.Expand]. The resulting string is returned. +func (re Reg) ReplaceAll(src string, repl string) string { + matches := re.FindAllSubmatch(src) + i := 0 + currentMatch := 0 + dst := "" + for i < len(src) { + 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++ + } else { + dst += string(src[i]) + i++ + } + } + return dst +}