This is an old revision of the document!


Useful regular expressions

A relatively advanced way to potentially semi-automate a few processes is the use of regular expressions. These are basically an advanced form of “find and replace” which can be very powerful. When used properly, they can clean up certain code and properly format things like footnotes in record time, or convert square bracket[1] style footnotes to without1 for print, and vice versa. For example, from the final Wellred InDesign book to EPUB export, we can now often achieve a 100% finished ebook in less than an hour thanks to a series of regular expressions executed at once.

The easiest way to understand the concept is to use a simple one. A fairly typical export from InDesign will have Headers as a paragraph tag, which isn't much use for HTML/EPUB:

Rather than

<p class=“Headings_Introduction-Title”>Chapter title</p>

we would like

<h1>Chapter title</h1>

Using regex, for the initial sequence (the “find” part of the find and replace) this becomes :

<p class=“Headings_Introduction-Title”>(.*?)</p>

(.*?) is a variable that captures everything in between the paragraph tag with class “Headings_Introduction-Title”.

To convert this to a proper <h1> tag we would replace this with:

<h1>\1</h1>

(with \1 being the “capture group”, the “replace” bit)

https://regex101.com/ is a useful resource to try out certain patterns.

Below are some further examples.

Clean paragraph tags

Replace

<p[^>]+>

with

<p>

remove span tags:

Replace

<[/]?span[^>]*>

with nothing

Remove empty paragraph tags:

Replace

<p[^>]*>&nbsp;</p>

with nothing

Replace

<p[^>]*>[ ]?</p>

with nothing

Bold paragraphs to h4:

Replace

<p[^>]*><strong>([^<]+)</strong></p>
<p[^>]*><b>([^<]+)</b></p>

With:

<h4>\1</h4>

Handling footnotes:

<a (href="#_ftn[0-9]") (name="_ftnref[0-9]") title=""></a>(\[[0-9]\])
<a (href="#_ftnref[0-9]") (name="_ftn[0-9]") title=""></a>(\[[0-9]\])
<a \2 /><a \1>\3</a>
<code>
<sup><a name="_ftnref\1" /><a href="#_ftn\1">\1</a></sup>
<a name="_ftn\1" /><a href="#_ftnref\1">\1</a>
<sup><a class="sdendnoteanc" (name="sdendnote[0-9]anc") (href="#sdendnote[0-9]sym")></a><sup>([a-z]*)</sup></sup>
<sup><a \1 /><a \2>\3</a></sup>
([\.”!])[ ]*([0-9]{1,2})([ <])
\1<sup><a name="_ftnref\2" /><a href="#_ftn\2">\2</a></sup>\3

Finding and replacing double quotation:

(?<!\=)"((?!"|'')[^"\n>]*)("|'')(?!>)(\W)
“\1”\3
<p>"([^"\n]+)</p>
<p>“\1</p>
(?<!\=)'((?!')[^'\n>]*)(')(?!>)(\W)
‘\1’\3

Removing line breaks in code:

This is useful if above isn't working because of line breaks. Replace

\n</p> 

with

</p>

Replace  

\r\n</p>

with

</p>