Skip to content

Commit

Permalink
regexp: improve ReplaceAllString documentation related to Expand part
Browse files Browse the repository at this point in the history
For #40329
  • Loading branch information
eduardbme committed Jul 25, 2020
1 parent 78c20c8 commit 6f0dca9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
13 changes: 11 additions & 2 deletions src/regexp/example_test.go
Expand Up @@ -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() {
Expand Down
7 changes: 5 additions & 2 deletions src/regexp/regexp.go
Expand Up @@ -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, "$") {
Expand Down

0 comments on commit 6f0dca9

Please sign in to comment.