Split content by regex and extract H2

Is it possible to extract H2 Headline from {{ page.content }} ? Something like:

{% for tabtitle = regex_filter(page.content, "/(?<=<h2>)(.*?)(?=</h2>)/") %}

{{ tabtitle }}

{% endfor %}

However I would not know how to split up page.content, to make that work. Also

And then get the text between the H2 headlines.

{% for tabcontent in regex_split(page.content, "/<h2>(.*?)</h2>/") %}

{{ tabcontent }}

{% endfor %}

I did not find any examples of that. Any ideas, how I would be able to do that?

@NEA, you might try to add your own filter/funtion to Twig, giving you full PHP functionality. See the docs: Custom Twig Filter/Function

I solved it. I had to add preg_match_all (matchall) as custom filter. The other part was possible with regex_replace and split:

{% for item in page.content|matchall('~(?<=<h2>)(.*?)(?=<\/h2>)~')[1] %}

{{ item }}

{% endfor %}
{% for item in regex_replace(page.content, ['~<h2>(.*?)</h2>~'], ['<hr />'])|split('<hr />')|slice(1) %}

        {{ item }}

{% endfor %}

@NEA, I think your reply would be so much more valuable to other community members if you add the definition of the custom filter you’ve created.