HUGO
Menu
GitHub 87548 stars Mastodon

strings.ReplaceRE

Returns a copy of INPUT, replacing all occurrences of a regular expression with a replacement pattern.

Syntax

strings.ReplaceRE PATTERN REPLACEMENT INPUT [LIMIT]

Returns

string

Alias

replaceRE

在指定正則表達式時,使用原始 [字符串字面量](反引號)而不是解釋字符串字面量(雙引號)以簡化語法。使用解釋字符串字面量時,您必須轉義反斜槓。

Go 的正則表達式包實現了 [RE2 語法]。RE2 語法是 PCRE 接受的內容的子集(粗略地說),並帶有各種 [注意事項]。請注意,不支持 RE2 \C 轉義序列。

{{ $s := "a-b--c---d" }}
{{ replaceRE `(-{2,})` "-" $s }} → a-b-c-d

Limit the number of replacements using the LIMIT argument:

{{ $s := "a-b--c---d" }}
{{ replaceRE `(-{2,})` "-" $s 1 }} → a-b-c---d

Use $1, $2, etc. within the replacement string to insert the content of each capturing group within the regular expression:

{{ $s := "http://gohugo.io/docs" }}
{{ replaceRE "^https?://([^/]+).*" "$1" $s }} → gohugo.io

You can write and test your regular expression using regex101.com. Be sure to select the Go flavor before you begin.


Last updated: January 1, 0001
Improve this page