Skip to content

Commit c017d4c

Browse files
committed
regexp: improve Regexp.ReplaceAll documentation and tests related to Expand part
Fixes #40329
1 parent f0894a0 commit c017d4c

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

src/regexp/example_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,11 +228,18 @@ func ExampleRegexp_ReplaceAll() {
228228
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
229229
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
230230
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
231+
232+
re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
233+
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
234+
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
235+
231236
// Output:
232237
// -T-T-
233238
// --xx-
234239
// ---
235240
// -W-xxW-
241+
// --xx-
242+
// -W-xxW-
236243
}
237244

238245
func ExampleRegexp_ReplaceAllLiteralString() {
@@ -252,11 +259,18 @@ func ExampleRegexp_ReplaceAllString() {
252259
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
253260
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
254261
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
262+
263+
re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
264+
fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
265+
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
266+
255267
// Output:
256268
// -T-T-
257269
// --xx-
258270
// ---
259271
// -W-xxW-
272+
// --xx-
273+
// -W-xxW-
260274
}
261275

262276
func ExampleRegexp_ReplaceAllStringFunc() {

src/regexp/regexp.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -573,8 +573,8 @@ 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+
// Inside repl, $ signs are interpreted as in Expand.
578578
func (re *Regexp) ReplaceAllString(src, repl string) string {
579579
n := 2
580580
if strings.Contains(repl, "$") {
@@ -672,8 +672,8 @@ func (re *Regexp) replaceAll(bsrc []byte, src string, nmatch int, repl func(dst
672672
}
673673

674674
// ReplaceAll returns a copy of src, replacing matches of the Regexp
675-
// with the replacement text repl. Inside repl, $ signs are interpreted as
676-
// in Expand, so for instance $1 represents the text of the first submatch.
675+
// with the replacement text repl.
676+
// Inside repl, $ signs are interpreted as in Expand.
677677
func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
678678
n := 2
679679
if bytes.IndexByte(repl, '$') >= 0 {

0 commit comments

Comments
 (0)