Golang Regexp.ReplaceAllLiteralString
最后修改于 2025 年 4 月 20 日
本教程将解释如何在 Go 中使用 Regexp.ReplaceAllLiteralString
方法。我们将介绍它与 ReplaceAllString
的区别,并提供示例。
一个 正则表达式 是一个定义搜索模式的字符序列。它用于在字符串中进行模式匹配。
Regexp.ReplaceAllLiteralString
方法用替换字符串替换正则表达式的所有匹配项。与 ReplaceAllString
不同,它将替换视为字面文本。
基本的 ReplaceAllLiteralString 示例
此示例展示了 Regexp.ReplaceAllLiteralString
最简单的用法,即用字面文本替换模式的所有出现。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`cat`) text := "The cat sat on the mat with another cat." result := re.ReplaceAllLiteralString(text, "dog") fmt.Println(result) }
代码将所有出现的“cat”替换为“dog”。替换被视为字面值,替换字符串没有任何特殊解释。
字面替换与非字面替换
此示例演示了在使用替换模式时 Regexp.ReplaceAllLiteralString
和 ReplaceAllString
之间的区别。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`(\d+)`) text := "Order 12345 has 3 items" literal := re.ReplaceAllLiteralString(text, "X$1X") nonLiteral := re.ReplaceAllString(text, "X$1X") fmt.Println("Literal:", literal) fmt.Println("Non-literal:", nonLiteral) }
Regexp.ReplaceAllLiteralString
将“$1”视为字面文本,而 Regexp.ReplaceAllString
则将其解释为组引用。输出清楚地显示了这种差异。
转义特殊字符
当您需要字面插入特殊字符时,Regexp.ReplaceAllLiteralString
非常有用。此示例将转义 HTML 标签。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`<.*?>`) html := "<p>Hello <b>world</b></p>" escaped := re.ReplaceAllLiteralString(html, "<tag>") fmt.Println(escaped) }
代码将所有 HTML 标签替换为字面字符串“<tag>”。替换被精确地按提供的方式处理,没有任何解释。
密码混淆
此示例使用 Regexp.ReplaceAllLiteralString
通过用星号替换密码来混淆日志消息中的密码。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`password=[^&\s]+`) log := "user=johndoe password=secret123 action=login" safeLog := re.ReplaceAllLiteralString(log, "password=*****") fmt.Println(safeLog) }
该模式匹配键值对中的密码值。替换使用字面星号来隐藏日志输出中的实际密码值。
URL 审查
在这里,我们使用 Regexp.ReplaceAllLiteralString
来审查 URL 中敏感部分,同时保留其结构。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`https://([^/]+)(/.*)`) url := "https://user:password@example.com/private/data" redacted := re.ReplaceAllLiteralString(url, "https://REDACTED$2") fmt.Println(redacted) }
该模式分别捕获域和路径。替换保留协议和路径,但用“REDACTED”字面替换凭据。
模板变量替换
此示例演示了如何将 Regexp.ReplaceAllLiteralString
用于简单的模板变量替换,其中变量应被视为字面值。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`\{\{(\w+)\}\}`) template := "Hello {{name}}, your code is {{code}}" result := re.ReplaceAllLiteralString(template, "VARIABLE") fmt.Println(result) }
所有模板变量({{name}}、{{code}})都被替换为字面字符串“VARIABLE”。当您想删除或标准化变量时,这非常有用。
特殊字符处理
最后一个示例演示了 Regexp.ReplaceAllLiteralString
如何处理替换字符串中的特殊字符。
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`\d+`) text := "The price is 100 dollars" // Replacement contains $ which would be special in ReplaceAllString result := re.ReplaceAllLiteralString(text, "$$$") fmt.Println(result) }
替换中的美元符号被视为字面字符。使用 Regexp.ReplaceAllString
,它们将被解释为组引用。
来源
本教程通过字面字符串替换场景的实际示例,涵盖了 Go 中的 Regexp.ReplaceAllLiteralString
方法。