# Is it possible to replace individual characters inside a regex capture group?

I’ve searched the forum for other solutions, but they don’t seem to answer the question I have in mind.

I want to add id attributes to all HTML header elements (e.g., h1, h2, h3, etc) using the content of each element as the basis for the id attribute, by making them lowercase and replacing spaces with hyphens.

For example, I simply want to do a replacement from this:

<h1>Primary Article</h1>
<h2>Subtopic</h2>
<h1>A Different Approach to All This</h1>


to this:

<h1 id="primary-article">Primary Article</h1>
<h2 id="subtopic">Subtopic</h2>
<h1 id="a-different-approach-to-all-this">A Different Approach to All This</h1>


This it the farthest I’ve gotten:

Search: <h(\d)>(.*?)</h\d>
Replace: <h\1 id="\L\2\E">\2</h\1>

It does everything I need, except replace the spaces in the capture group with dashes. Is this even possible?

If not, how would you approach this problem?