Case study

Let's build a basic regular expression-powered templating engine in Python. This engine will parse a text file (such as an HTML page) and replace certain directives with text calculated from the input to those directives. This is about the most complicated task we would want to do with regular expressions; indeed, a full-fledged version of this would likely utilize a proper language parsing mechanism.

Consider the following input file:

/** include header.html **/ <h1>This is the title of the front page</h1> /** include menu.html **/ <p>My name is /** variable name **/. This is the content of my front page. It goes below the menu.</p> <table> <tr><th>Favourite Books</th></tr> /** loopover book_list **/ <tr><td>/** loopvar **/</td></tr> ...

Get Python: Journey from Novice to Expert now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.