diff options
author | Cameron Moore <moorereason@gmail.com> | 2020-08-28 09:29:26 -0500 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2020-08-28 18:57:56 +0200 |
commit | cdfd1c99baa22d69e865294dfcd783811f96c880 (patch) | |
tree | 0e2e21537de208baf493318c0e38b2b1631f7c8f /tpl/strings/regexp.go | |
parent | 047af7cfe5e9aa740b85e0f9974a2d31a0ef4c08 (diff) |
tpl: Add limit support to replaceRE
Go stdlib doesn't contain a limited replace in the regexp package, but
we can accomplish the same thing with ReplaceAllStringFunc.
Fixes #7586
Diffstat (limited to 'tpl/strings/regexp.go')
-rw-r--r-- | tpl/strings/regexp.go | 22 |
1 files changed, 19 insertions, 3 deletions
diff --git a/tpl/strings/regexp.go b/tpl/strings/regexp.go index 7b52c9f6e..c6d731a0d 100644 --- a/tpl/strings/regexp.go +++ b/tpl/strings/regexp.go @@ -46,8 +46,9 @@ func (ns *Namespace) FindRE(expr string, content interface{}, limit ...interface } // ReplaceRE returns a copy of s, replacing all matches of the regular -// expression pattern with the replacement text repl. -func (ns *Namespace) ReplaceRE(pattern, repl, s interface{}) (_ string, err error) { +// expression pattern with the replacement text repl. The number of replacements +// can be limited with an optional fourth parameter. +func (ns *Namespace) ReplaceRE(pattern, repl, s interface{}, n ...interface{}) (_ string, err error) { sp, err := cast.ToStringE(pattern) if err != nil { return @@ -63,12 +64,27 @@ func (ns *Namespace) ReplaceRE(pattern, repl, s interface{}) (_ string, err erro return } + nn := -1 + if len(n) > 0 { + nn, err = cast.ToIntE(n[0]) + if err != nil { + return + } + } + re, err := reCache.Get(sp) if err != nil { return "", err } - return re.ReplaceAllString(ss, sr), nil + return re.ReplaceAllStringFunc(ss, func(str string) string { + if nn == 0 { + return str + } + + nn -= 1 + return re.ReplaceAllString(str, sr) + }), nil } // regexpCache represents a cache of regexp objects protected by a mutex. |