Skip to content

Instantly share code, notes, and snippets.

@dandv
Created November 26, 2008 08:37
Show Gist options
  • Save dandv/29326 to your computer and use it in GitHub Desktop.
Save dandv/29326 to your computer and use it in GitHub Desktop.
use strict;
my $content = '=toc<br />
=toc 2-4<br />
<p>=toc 2</p>
<div id="stff">=toc -3<br />
<p>=toc 2-</p>
';
my ($toc_h_min, $toc_h_max);
my $toc_params_RE = qr/\s+ (\d*)(?{$toc_h_min = $^N}) \s* - \s* (\d*)(?{$toc_h_max = $^N})/x;
while (
# replace the =toc markup tag if it's on a line of its own (<p>), or not (followed by <br />)
$content =~ s{
<p>=toc(?:$toc_params_RE)? \s* </p>
| (?:<=>)?=toc(?:$toc_params_RE)? \s* (?=<br)
}{<!--mojomojoTOCwillgohere-->}x) {
$toc_h_min ||= 1, $toc_h_max ||= 12;
# FIXME: Perl 5.10 has a regexp branch reset operator which simplifies this
#if ($1) {
# # matched the <p> branch
# $toc_h_min = $2 || 1;
# $toc_h_max = $4 || 12;
#} else {
# # matched the <br branch
# $toc_h_min = $4 || 1;
# $toc_h_max = $5 || 12; # 6 is the HTML max, but hey, knock yourself out
#}
print "$toc_h_min - $toc_h_max\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment