![]() Back to www.deitel.com |
1 # Fig. 35.12: fig35_12.py
|
2 # Program searches a string using the regular expression module.
|
3
|
4 import re
|
5
|
6 searchString = "Testing pattern matches"
|
7
|
8 expression1 = re.compile( r"Test" )
|
9 expression2 = re.compile( r"^Test" )
|
10 expression3 = re.compile( r"Test$" )
|
11 expression4 = re.compile( r"\b\w*es\b" )
|
12 expression5 = re.compile( r"t[aeiou]", re.I )
|
13
|
14 if expression1.search( searchString ):
|
15 print '"Test" was found.'
|
16
|
17 if expression2.match( searchString ):
|
18 print '"Test" was found at the beginning of the line.'
|
19
|
20 if expression3.match( searchString ):
|
21 print '"Test" was found at the end of the line.'
|
22
|
23 result = expression4.findall( searchString )
|
24
|
25 if result:
|
26 print 'There are %d words(s) ending in "es":' % \
|
27 ( len( result ) ),
|
28
|
29 for item in result:
|
30 print " " + item,
|
31
|
32 print
|
33 result = expression5.findall( searchString )
|
34
|
35 if result:
|
36 print 'The letter t, followed by a vowel, occurs %d times:' % \
|
37 ( len( result ) ),
|
38
|
39 for item in result:
|
40 print " " + item,
|
41
|
42 print
|
"Test" was found.
"Test" was found at the beginning of the line.
There are 1 words(s) ending in "es": matches
The letter t, followed by a vowel, occurs 3 times: Te ti te
|