From 6f0dca9153ebd2341eebb0afe6ee851193eea268 Mon Sep 17 00:00:00 2001 From: Eduard Bondarenko Date: Fri, 24 Jul 2020 16:52:53 +0300 Subject: [PATCH] regexp: improve ReplaceAllString documentation related to Expand part For #40329 --- src/regexp/example_test.go | 13 +++++++++++-- src/regexp/regexp.go | 7 +++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/regexp/example_test.go b/src/regexp/example_test.go index 466b38b0fa2aa4..0224d65d00af97 100644 --- a/src/regexp/example_test.go +++ b/src/regexp/example_test.go @@ -226,13 +226,22 @@ func ExampleRegexp_ReplaceAll() { re := regexp.MustCompile(`a(x*)b`) fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T"))) fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1"))) - fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W"))) fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W"))) + + // $1W evaluated as ${1W} + // $1W is not a named submatch, so the replacement is with an empty slice. + fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W"))) + + re2 := regexp.MustCompile(`a(?P<1W>x*)b`) + // $1W is a named submatch, so the replacement is with a matched slice. + fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W"))) + // Output: // -T-T- // --xx- - // --- // -W-xxW- + // --- + // --xx- } func ExampleRegexp_ReplaceAllLiteralString() { diff --git a/src/regexp/regexp.go b/src/regexp/regexp.go index b547a2ab97d71a..830fb395b51581 100644 --- a/src/regexp/regexp.go +++ b/src/regexp/regexp.go @@ -565,8 +565,11 @@ func Match(pattern string, b []byte) (matched bool, err error) { } // ReplaceAllString returns a copy of src, replacing matches of the Regexp -// with the replacement string repl. Inside repl, $ signs are interpreted as -// in Expand, so for instance $1 represents the text of the first submatch. +// with the replacement string repl. +// +// Inside repl, $ signs are interpreted as in Expand, +// so for instance $1 represents the text of the first submatch, +// and "$1x" is equivalent to "${1x}", not "${1}x". func (re *Regexp) ReplaceAllString(src, repl string) string { n := 2 if strings.Contains(repl, "$") {