strings.FindRESubmatch
语法
strings.FindRESubmatch PATTERN INPUT [LIMIT]
返回值
[][]string
别名
findRESubmatch
默认情况下,findRESubmatch
查找所有匹配项。您可以使用可选的 LIMIT 参数限制匹配项的数量。返回 nil 表示没有匹配项。
指定正则表达式时,请使用原始字符串字面量(反引号)而不是解释字符串字面量(双引号)来简化语法。使用解释字符串字面量时,必须转义反斜杠。
Go 的正则表达式包实现了 RE2 语法。RE2 语法是 PCRE 接受的语法的子集,粗略地说,并且存在各种 注意事项。请注意,不支持 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.com.cn)
生成此 HTML
<ul>
<li><a href="https://example.org">Example</a></li>
<li><a href="https://gohugo.com.cn">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.com.cn\">Hugo</a>",
"https://gohugo.com.cn",
"Hugo"
]
]
渲染 href
属性
{{ range $matches }}
{{ index . 1 }}
{{ end }}
结果
https://example.org
https://gohugo.com.cn