Regular
expressions exercise 1
- Run this program. What does it do? What does the method
end() do which you can call on an SRE_Match object
(the resulting object you get from a regular expression search)?
- Modify the program so it finds the indices of all letters in the
string.
- Write a new program that reads in some python program file and
uses regular expressions to find all
print "< something >" statements in the
file and prints out all the "< something >"'s. E.g., if the program
you read in contains the sentence
print "Account balance:",
balance
your new program should print "Account balance:".
import re
reg = "\d"
text = "012345abcd"
start_index = 0
SRE_Match = re.compile( reg )
result = SRE_Match.search( text[start_index: ] )
while result:
print result.group(), "found at index", (result.end() + start_index -1)
start_index += result.end()
result = SRE_Match.search( text[start_index: ] )