NewReplacer Multi-Pair Text Rewrites

Rewrite many substrings in one pass with strings.NewReplacer: pairs compete by argument order, matches never overlap, and the replacer is reusable.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	// NewReplacer:成对给出 old/new,一次扫描完成全部替换
	sanitize := strings.NewReplacer(
		"<", "&lt;",
		">", "&gt;",
		"&", "&amp;",
	)
	fmt.Println(sanitize.Replace("a < b & c > d"))

	// 长度不等也允许:统一破折号、压掉重复空格
	normalize := strings.NewReplacer(
		"–", "-",
		"—", "-",
		"  ", " ",
	)
	fmt.Println(normalize.Replace("2026—11—12  draft–v2  notes"))

	// Replacer 不可变且并发安全:构造一次,处处复用
	fmt.Println(sanitize.Replace("5 > 3 & 1 < 2"))
}

How it works

NewReplacer Multi-Pair Text Rewrites reduces to the function main.

Two replacers are built once in main and reused. sanitize registers three pairs — < to &lt;, > to &gt;, & to &amp; — and rewriting a < b & c > d completes in a single scan. normalize unifies en-dashes and em-dashes to plain hyphens and collapses double spaces, as the comment describes. The closing call runs sanitize again over 5 > 3 & 1 < 2, showing that a Replacer is immutable and safe to reuse; replacement output is never rescanned, so pairs compete only at each input position, in argument order.

Interactive Tools for This Topic

FAQ

How do you run NewReplacer Multi-Pair Text Rewrites?
Just run the file; everything it needs ships with the runtime itself.