Skip to content

Commit 7de990e

Browse files
committed
doc: improve re.ReplaceAllString documentation related to Expand part
1 parent 78c20c8 commit 7de990e

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+
// IMPORTANT
232+
// $1W considered as ${1W}, NOT ${1}W. As a result you will receive ---
233+
// Chances are this is not what you expect. Take a look of how Expand works.
234+
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
235+
236+
re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
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
@@ -565,8 +565,11 @@ func Match(pattern string, b []byte) (matched bool, err error) {
565565
}
566566

567567
// ReplaceAllString returns a copy of src, replacing matches of the Regexp
568-
// with the replacement string repl. Inside repl, $ signs are interpreted as
569-
// in Expand, so for instance $1 represents the text of the first submatch.
568+
// with the replacement string repl.
569+
//
570+
// Inside repl, $ signs are interpreted as in Expand,
571+
// so for instance $1 represents the text of the first submatch,
572+
// but "$1W" evaluated as "${1W}", not "${1}W"
570573
func (re *Regexp) ReplaceAllString(src, repl string) string {
571574
n := 2
572575
if strings.Contains(repl, "$") {

0 commit comments

Comments
 (0)