Wrote ReplaceAll(), to replace all matches of the regex with a given string

implementBackreferences
Aadhavan Srinivasan 4 weeks ago
parent 5ab95f512a
commit 50221ff4d9

@ -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
}

Loading…
Cancel
Save