Skip to content

Commit

Permalink
regexp: improve Regexp.ReplaceAll documentation and tests related to …
Browse files Browse the repository at this point in the history
…Expand part

Fixes #40329
  • Loading branch information
eduardbme committed Aug 1, 2023
1 parent f0894a0 commit c017d4c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
14 changes: 14 additions & 0 deletions src/regexp/example_test.go
Expand Up @@ -228,11 +228,18 @@ func ExampleRegexp_ReplaceAll() {
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")))

re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))

// Output:
// -T-T-
// --xx-
// ---
// -W-xxW-
// --xx-
// -W-xxW-
}

func ExampleRegexp_ReplaceAllLiteralString() {
Expand All @@ -252,11 +259,18 @@ func ExampleRegexp_ReplaceAllString() {
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))

re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))

// Output:
// -T-T-
// --xx-
// ---
// -W-xxW-
// --xx-
// -W-xxW-
}

func ExampleRegexp_ReplaceAllStringFunc() {
Expand Down
8 changes: 4 additions & 4 deletions src/regexp/regexp.go
Expand Up @@ -573,8 +573,8 @@ 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.
func (re *Regexp) ReplaceAllString(src, repl string) string {
n := 2
if strings.Contains(repl, "$") {
Expand Down Expand Up @@ -672,8 +672,8 @@ func (re *Regexp) replaceAll(bsrc []byte, src string, nmatch int, repl func(dst
}

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

0 comments on commit c017d4c

Please sign in to comment.