regexp: fix index panic in Replace

When using subexpressions ($1) as replacements, when they either don't exist or values weren't found causes a panic.
This patch ensures that the match location isn't -1, to prevent out of bounds errors.
Fixes #3816.

R=franciscossouza, rsc
CC=golang-dev
https://golang.org/cl/6931049
This commit is contained in:
Erik St. Martin 2012-12-22 11:14:56 -05:00 committed by Russ Cox
parent 90a85dbefc
commit 54b7ccd514
2 changed files with 5 additions and 1 deletions

View file

@ -196,6 +196,10 @@ var replaceTests = []ReplaceTest{
{"a+", "${oops", "aaa", "${oops"}, {"a+", "${oops", "aaa", "${oops"},
{"a+", "$$", "aaa", "$"}, {"a+", "$$", "aaa", "$"},
{"a+", "$", "aaa", "$"}, {"a+", "$", "aaa", "$"},
// Substitution when subexpression isn't found
{"(x)?", "$1", "123", "123"},
{"abc", "$1", "123", "123"},
} }
var replaceLiteralTests = []ReplaceTest{ var replaceLiteralTests = []ReplaceTest{

View file

@ -767,7 +767,7 @@ func (re *Regexp) expand(dst []byte, template string, bsrc []byte, src string, m
} }
template = rest template = rest
if num >= 0 { if num >= 0 {
if 2*num+1 < len(match) { if 2*num+1 < len(match) && match[2*num] >= 0 {
if bsrc != nil { if bsrc != nil {
dst = append(dst, bsrc[match[2*num]:match[2*num+1]]...) dst = append(dst, bsrc[match[2*num]:match[2*num+1]]...)
} else { } else {