Skip to content

Commit b844347

Browse files
committed
regexp: improve Regexp.ReplaceAllString documentation related to Expand part
Fixes #40329
1 parent f0894a0 commit b844347

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/regexp/example_test.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,13 +226,22 @@ func ExampleRegexp_ReplaceAll() {
226226
re := regexp.MustCompile(`a(x*)b`)
227227
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
228228
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
229-
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
230229
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
230+
231+
// $1W evaluated as ${1W}
232+
// $1W is not a named submatch, so the replacement is with an empty slice.
233+
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
234+
235+
re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
236+
// $1W is a named submatch, so the replacement is with a matched slice.
237+
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
238+
231239
// Output:
232240
// -T-T-
233241
// --xx-
234-
// ---
235242
// -W-xxW-
243+
// ---
244+
// --xx-
236245
}
237246

238247
func ExampleRegexp_ReplaceAllLiteralString() {

src/regexp/regexp.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -573,8 +573,11 @@ func Match(pattern string, b []byte) (matched bool, err error) {
573573
}
574574

575575
// ReplaceAllString returns a copy of src, replacing matches of the Regexp
576-
// with the replacement string repl. Inside repl, $ signs are interpreted as
577-
// in Expand, so for instance $1 represents the text of the first submatch.
576+
// with the replacement string repl.
577+
//
578+
// Inside repl, $ signs are interpreted as in Expand,
579+
// so for instance $1 represents the text of the first submatch,
580+
// and "$1x" is equivalent to "${1x}", not "${1}x".
578581
func (re *Regexp) ReplaceAllString(src, repl string) string {
579582
n := 2
580583
if strings.Contains(repl, "$") {

0 commit comments

Comments
 (0)