from stephen marquard@uct ac za sat jan : : and wanted to extract the hour of the day for each line previously we did this with two calls to split first the line was split into words and then we pulled out the fifth word and split it again on the colon character to pull out the two characters we were interested in while this workedit actually results in pretty brittle code that is assuming the lines are nicely formatted if you were to add enough error checking (or big try/except blockto insure that your program never failed when presented with incorrectly formatted linesthe code would balloon to - lines of code that was pretty hard to read we can do this in far simpler way with the following regular expression^from [ - ][ - ]the translation of this regular expression is that we are looking for lines that start with from (note the space)followed by any number of characters *)followed by spacefollowed by two digits [ - ][ - ]followed by colon character this is the definition of the kinds of lines we are looking for in order to pull out only the hour using findall()we add parentheses around the two digits as follows^from ([ - ][ - ])this results in the following programsearch for lines that start with from and character followed by two digit number between and followed by ':then print the number if it is greater than zero import re hand open('mbox-short txt'for line in handline line rstrip( re findall('^from ([ - ][ - ]):'lineif len( print(xcodewhen the program runsit produces the following output[' '[' '[' '[' '