Skip to content

doc: improve re.ReplaceAllString documentation related to Expand part #40389

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/regexp/example_test.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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