strings.FindRESubmatch
預設情況下,findRESubmatch
會找到所有匹配項。您可以使用可選的 LIMIT
引數來限制匹配的數量。返回值為 nil 表示無匹配項。
在指定正則表達式時,請使用原始的 string literal(反引號),而非解釋過的字串字面量(雙引號),以簡化語法。使用解釋過的字串字面量時,您必須對反斜線進行轉義。
Go 的正則表達式套件實現了 [RE2 語法]。RE2 語法是接受的 PCRE 語法的一個子集,粗略來說,並且有各種 caveats。請注意,RE2 不支援 \C
轉義序列。
示範範例
{{ findRESubmatch `a(x*)b` "-ab-" }} → [["ab" ""]]
{{ findRESubmatch `a(x*)b` "-axxb-" }} → [["axxb" "xx"]]
{{ findRESubmatch `a(x*)b` "-ab-axb-" }} → [["ab" ""] ["axb" "x"]]
{{ findRESubmatch `a(x*)b` "-axxb-ab-" }} → [["axxb" "xx"] ["ab" ""]]
{{ findRESubmatch `a(x*)b` "-axxb-ab-" 1 }} → [["axxb" "xx"]]
實務範例
這段 Markdown:
- [Example](https://example.org)
- [Hugo](https://gohugo.io)
產生的 HTML:
<ul>
<li><a href="https://example.org">Example</a></li>
<li><a href="https://gohugo.io">Hugo</a></li>
</ul>
要匹配超連結元素,並捕捉連結目標與文字:
{{ $regex := `<a\s*href="(.+?)">(.+?)</a>` }}
{{ $matches := findRESubmatch $regex .Content }}
JSON 格式的 $matches
資料結構範例如下:
[
[
"<a href=\"https://example.org\"></a>Example</a>",
"https://example.org",
"Example"
],
[
"<a href=\"https://gohugo.io\">Hugo</a>",
"https://gohugo.io",
"Hugo"
]
]
要顯示 href
屬性的值:
{{ range $matches }}
{{ index . 1 }}
{{ end }}
結果:
https://example.org
https://gohugo.io