generate in-page TOCs on demand

This commit is contained in:
Mark Pilgrim
2009-03-19 01:42:12 -04:00
parent cfeee5d73d
commit 3b9c6c67e9
8 changed files with 29 additions and 189 deletions
+1 -16
View File
@@ -13,22 +13,7 @@ body{counter-reset:h1 4}
<blockquote class=q>
<p><span>&#x275D;</span> Some people, when confronted with a problem, think &#8220;I know, I&#8217;ll use regular expressions.&#8221; Now they have two problems. <span>&#x275E;</span><br>&mdash; <cite>Jamie Zawinski</cite>
</blockquote>
<ol>
<li><a href=#divingin>Diving in</a>
<li><a href=#streetaddresses>Case study: street addresses</a>
<li><a href=#romannumerals>Case study: Roman numerals</a>
<ol>
<li><a href=#thousands>Checking for thousands</a>
<li><a href=#hundreds>Checking for hundreds</a>
</ol>
<li><a href=#nmsyntax>Using the <code>{n,m}</code> Syntax</a>
<ol>
<li><a href=#tensandones>Checking for tens and ones</a>
</ol>
<li><a href=#verbosere>Verbose regular expressions</a>
<li><a href=#phonenumbers>Case study: parsing phone numbers</a>
<li><a href=#summary>Summary</a>
</ol>
<p id=toc>&nbsp;
<h2 id=divingin>Diving in</h2>
<p class=f>Every modern programming language has built-in functions for working with strings. In Python, strings have methods for searching and replacing: <code>index()</code>, <code>find()</code>, <code>split()</code>, <code>count()</code>, <code>replace()</code>, <i class=baa>&amp;</i>c. But these methods are limited to the simplest of cases. For example, the <code>index()</code> method looks for a single, hard-coded substring, and the search is always case-sensitive. To do case-insensitive searches of a string <var>s</var>, you must call <code>s.lower()</code> or <code>s.upper()</code> and make sure your search strings are the appropriate case to match. The <code>replace()</code> and <code>split()</code> methods have the same limitations.
<p>If your goal can be accomplished with string methods, you should use them. They&#8217;re fast and simple and easy to read, and there&#8217;s a lot to be said for fast, simple, readable code. But if you find yourself using a lot of different string functions with <code>if</code> statements to handle special cases, or if you&#8217;re chaining calls to <code>split()</code> and <code>join()</code> to slice-and-dice your strings, you may need to move up to regular expressions.