Skip to main content

findRESubmatch

Returns a slice of all successive matches of the regular expression. Each element is a slice of strings holding the text of the leftmost match of the regular expression and the matches, if any, of its subexpressions.

デフォルトでは、findRESubmatch はすべての一致を検索します。 オプションの LIMIT パラメータを使用して、一致の数を制限できます。 戻り値 nil は一致しないことを示します。

正規表現を指定するときは、構文を簡略化するために、解釈された文字列リテラル (二重引用符) の代わりに生の 文字列リテラル  (バックティック/バッククォート) を使用します。 解釈された文字列リテラルでは、バックスラッシュをエスケープする必要があります。

この関数は RE2  正規表現ライブラリを使用します。 詳細については、RE2 構文ドキュメント  を参照してください。 RE2 の \C エスケープ シーケンスがサポートされていないことに注意してください。

で受け入れられているもののサブセットであり、さまざまな <a href=“https://swtch.com/~rsc/regexp/regexp3.html#caveats"target="_blank"  rel=“noopener”>注意事項 

があります。

実証例

{{ 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>

To match the anchor elements, capturing the link destination and text:

{{ $regex := `<a\s*href="(.+?)">(.+?)</a>` }}
{{ $matches := findRESubmatch $regex .Content }}

リンク先とテキストをキャプチャしてアンカー要素を照合するには、以下のようにします。

[
  [
    "<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

を使って正規表現を書き、テストすることができます。 始める前に必ず Go フレーバーを選択してください。