Rewrite Text With regexp ReplaceAll
Substitute matches with capture groups using $1 indexes and ${name} named references, including the brace form that delimits adjacent text.
Code
package main
import (
"fmt"
"regexp"
)
func main() {
// 具名捕获组:替换模板里用 ${name} 引用
logLine := regexp.MustCompile("^(?P<level>INFO|WARN) (?P<msg>.*)$")
fmt.Println(logLine.ReplaceAllString("WARN disk almost full", "[${level}] ${msg}"))
// 日期重排:$1/$2/$3 按组序号引用
date := regexp.MustCompile("(\d{4})-(\d{2})-(\d{2})")
fmt.Println(date.ReplaceAllString("deployed 2026-11-15, verified 2026-11-14", "$3/$2/$1"))
// 组名后紧跟普通字符时必须用大括号定界,否则会被当成更长的组名
env := regexp.MustCompile("(\w+)=(\w+)")
fmt.Println(env.ReplaceAllString("env=prod region=eu", "$1: ${2};"))
}Group references in templates
Replacement strings can name capture groups: $1/$2 refer to groups by index, and ${name} refers to named groups. The first rewrite uses the named pair level/msg from (?P
The brace rule
When a group reference is followed by an ordinary character, the name must be delimited with braces — ${2}; — otherwise the engine reads a longer group name and the reference fails. The env rewrite shows both forms: $1: ${2};
Why MustCompile
Both patterns are compiled once at package init with regexp.MustCompile; a malformed pattern panics at startup instead of failing on every call.
Interactive Tools for This Topic
FAQ
- Why must ${name} use braces in some templates?
- Without braces the engine consumes following word characters as part of the group name, so a reference followed by text needs the brace form to mark where the name ends.
- What does MustCompile trade for safety?
- It panics at package init on an invalid pattern instead of returning an error per call — appropriate for compile-time constant patterns.
Report a problem with this exampleOpens a pre-filled issue on GitHub.