The match() and search() regular expression functions return either a True Boolean value if
the text string matches the regular expression pattern or a False value if they don’t match. This
makes them ideal for use in if-then statements.
The match() Function
The match() function does what it says: It tries to match the regular expression pattern to a text
string. It is a little tricky in that it applies the regular expression string only to the start of the string
value. Here’s an example:
Click here to view code image
>>> re.match('test', 'testing')
<_sre.SRE_Match object at 0x015F9950>
>>> re.match('ing', 'testing')
>>>
The output from the first match indicates that the match was successful. When the match fails, the
match() function just returns a False value, which doesn’t show any output in the IDLE interface.
The search() Function
The search() function is a lot more versatile than match(): It applies the regular expression
pattern to an entire string and returns a True value if it finds the pattern anywhere in the string.
Here’s an example:
Click here to view code image
>>> re.search('ing', 'testing')
<_sre.SRE_Match object at 0x015F9918>
>>>
This output from the search() function indicates that it found the pattern inside the string.
The findall() and finditer() Functions
Both the findall() and finditer() functions returns multiple instances of the pattern if it is
found in the string. The findall() function returns a list of values that match in the string, as you
can see here:
Click here to view code image
>>> re.findall('[ch]at', 'The cat wore a hat')
['cat', 'hat']
>>>
The finditer() function returns an iterable object that you can use in a for statement to iterate
through the results.
Compiled Regular Expressions
If you find yourself using the same regular expression often in your code, you can compile the
expression and store it in a variable. You can then use the variable everywhere in your code that you
want to perform the regular expression pattern match.
To compile an expression, you use the compile() function, specifying the regular expression as the
parameter and storing the result in a variable, like this:
Click here to view code image