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

(singke) #1

this example:


Click here to view code image


>>> re.search('test', 'This is a test')
<_sre.SRE_Match object at 0x015F99C0>
>>> re.search('test', 'This is not going to work')
>>>

With the search() function, the regular expression doesn’t care where in the data the pattern
occurs. It also doesn’t matter how many times the pattern occurs. When the regular expression can
match the pattern anywhere in the text string, it returns a True value.


The key is matching the regular expression pattern to the text. It’s important to remember that regular
expressions are extremely picky about matching patterns. Remember that, by default, regular
expression patterns are case sensitive. This means they’ll match patterns only for the proper case of
characters, as shown here:


Click here to view code image


>>> re.search('this', 'This is a test')
>>>
>>> re.search('This', 'This is a test')
<_sre.SRE_Match object at 0x015F9988>
>>>

The first attempt here fails to match because the word this doesn’t appear in all lowercase in the
text string; the second attempt, using the uppercase letter in the pattern, works just fine.


You don’t have to limit yourself to whole words in a regular expression. If the defined text appears
anywhere in the data stream, the regular expression will match, as shown here:


Click here to view code image


>>> re.search('book', 'The books are expensive')
<_sre.SRE_Match object at 0x015F99C0>
>>>

Even though the text in the data stream is books, the data in the stream contains the regular expression
book, so the regular expression pattern matches the data. Of course, if you try the opposite, the
regular expression fails, as shown in this example:


Click here to view code image


>>> re.search('books', 'The book is expensive')
>>>

You also don’t have to limit yourself to single text words in a regular expression. You can include
spaces and numbers in your text string as well, as shown here:


Click here to view code image


>>> re.search('This is line number 1', 'This is line number 1')
<_sre.SRE_Match object at 0x015F9988>
>>> re.search('ber 1', 'This is line number 1')
<_sre.SRE_Match object at 0x015F99F8>
>>> re.search('ber 1', 'This is line number1')
>>>

If you define a space in a regular expression, it must appear in the data stream. You can even create a

Free download pdf