diff --git a/src/regexp/all_test.go b/src/regexp/all_test.go index d78ae6a4cd..9448f60624 100644 --- a/src/regexp/all_test.go +++ b/src/regexp/all_test.go @@ -201,6 +201,12 @@ var replaceTests = []ReplaceTest{ // Substitution when subexpression isn't found {"(x)?", "$1", "123", "123"}, {"abc", "$1", "123", "123"}, + + // Substitutions involving a (x){0} + {"(a)(b){0}(c)", ".$1|$3.", "xacxacx", "x.a|c.x.a|c.x"}, + {"(a)(((b))){0}c", ".$1.", "xacxacx", "x.a.x.a.x"}, + {"((a(b){0}){3}){5}(h)", "y caramb$2", "say aaaaaaaaaaaaaaaah", "say ay caramba"}, + {"((a(b){0}){3}){5}h", "y caramb$2", "say aaaaaaaaaaaaaaaah", "say ay caramba"}, } var replaceLiteralTests = []ReplaceTest{ diff --git a/src/regexp/regexp.go b/src/regexp/regexp.go index 4e4b41242a..85c070eaeb 100644 --- a/src/regexp/regexp.go +++ b/src/regexp/regexp.go @@ -482,6 +482,10 @@ func (re *Regexp) replaceAll(bsrc []byte, src string, nmatch int, repl func(dst } else { endPos = len(src) } + if nmatch > re.prog.NumCap { + nmatch = re.prog.NumCap + } + for searchPos <= endPos { a := re.doExecute(nil, bsrc, src, searchPos, nmatch) if len(a) == 0 {