content_image/709817.jpg
You can learn about this by interactively experimenting with the$_{re}$ module. If you have$_{tkinter}$ available, you may also want to look at Tools/demo/redemo.py, a demonstration program included with the Python distribution. It allows you to enter REs and strings, and displays whether the RE matches or fails.$_{redemo.py}$can be quite useful when trying to debug a complicated RE. 

This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the$_{re}$ module, and compile a RE: 

>>>import re >>> p =re.compile( '[a-z]+') >>> p re.compile('[a-z]+') 

Now, you can try matching various strings against the RE [a-z]+ . An empty string shouldn’t match at all, since + means ‘one or more repetitions’. match() should return None in this case, which will cause the interpreter to print no output. You can explicitly print the result of$_{match()}$ to make this clear. 

>>> p.match("") >>> print(p.match("")) None 

Now, let’s try it on a string that it should match, such as tempo . In this case, match() will return a match object, so you should store the result in a variable for later use. 

>>> m =p.match('tempo') >>> m <re.Match object; span=(0, 5), match='tempo'> 

Now you can query the match object for information about the matching string. Match object instances also have several methods and attributes; the most important ones are: 

Trying these methods will soon clarify their meaning: 

>>> m.group() 'tempo' >>> m.start(), m .end() (0, 5) >>> m.span() (0, 5) 

<img src='content_image/709817.jpg'>

group() returns the substring that was matched by the RE.$_{start()}$ and$_{end()}$ return the starting and ending index of the match.$_{span()}$ returns both start and end indexes in a single tuple. Since the$_{match()}$ method only checks if the RE matches at the start of a string,$_{start()}$ will always be zero. However, the$_{search()}$ method of patterns scans through the string, so the match may not start at zero in that case. 

>>> print(p.match('::: message ')) None >>> m =p.search('::: message ');print(m) <re.Match object; span=(4, 11), match='message'> >>> m.group() 'message' >>> m.span() (4, 11) 

