Main Content

Regular Expressions in Python

Archive - Originally posted on "The Horse's Mouth" - 2010-04-14 00:33:29 - Graham Ellis

I took advantage of the lack of a whiteboard yesterday to write notes on the screen - in an edit window - while I was teaching a class about regular expressions, and how they're used in Python. Which has resulted in a rather nice example that's now online [here].

Regular expressions can frighten newcomers. At time they appear to the uninitiated to be impenetrable strings of characters, but take a careful look, break them down into literals, groups, counts and assertions, and they become much more straightforward. I've put examples a summary of what each of the types is, together with some examples, in comments at the top of the training code.

My Python Regular Expression Example matches email addresses, splits an HTML stream into tags and content, and recognizes both the sort and long form of USA postcodes. As I was giving a Python Course in Dublin, I didn't use my more regular British postcode example as my delegates were unlikely to be familiar with the details of how those are formatted.