Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
>>> pattern = re.compile('[ch]at')

After you store the compiled regular expression, you can use it directly in a match() or
search() function, as shown here:


Click here to view code image


>>> pattern.search('This is a cat')
<_sre.SRE_Match object at 0x015F9988>
>>> pattern.search('He wore a hat')
<_sre.SRE_Match object at 0x015F9918>
>>> pattern.search('He sat in a chair')
>>>

The additional benefit of using compiled regular expression patterns is that you can also specify flags
to control special features of the regular expression match. Table 16.2 shows these flags and what
they control.


TABLE 16.2 Compiled Flags

For example, by default, regular expression matches are case sensitive. To make a check case
insensitive, you just compile the regular expression with the re.I flag, as shown here:


Click here to view code image


>>> pattern = re.compile('[ch]at', re.I)
>>> pattern.search('Cat')
<_sre.SRE_Match object at 0x015F9988>
>>> pattern.search('Hat')
<_sre.SRE_Match object at 0x015F9918>
>>>

The search() function can now match the text in either uppercase or lowercase, anywhere in the
text.


Defining Basic Patterns


Defining regular expression patterns falls somewhere between a science and an art form. Entire
books have been written about how to create regular expressions for matching different types of data
(such as email addresses, phone numbers, or Social Security numbers). Instead of just showing a list
of different regular expression patterns, the purpose of this section is to provide the basics of how to
use them in daily text searches.


Plain Text


The simplest pattern for searching for text is to use the text that you want to find in its entirety, as in

Free download pdf