Alex Rivera | Logout

Match start and end of file in python with regex

Asked 2010-03-02T10:37:57.877
11

I'm having a hard time finding the regex for the start and end of a file in python. How would I accomplish this ?

Edit
Report

1 Answer

20

Read the whole file into a string, then \A matches only the beginning of a string, and \Z matches only the end of a string. With re.MULTILINE, '^' matches the beginning of the string and the just after a newline, and '$' matches the end of the string and just before a newline. See the Python documentation for re syntax.

import re

data = '''sentence one.
sentence two.
a bad sentence
sentence three.
sentence four.'''

# find lines ending in a period
print re.findall(r'^.*\.$',data,re.MULTILINE)
# match if the first line ends in a period
print re.findall(r'\A^.*\.$',data,re.MULTILINE)
# match if the last line ends in a period.
print re.findall(r'^.*\.$\Z',data,re.MULTILINE)

Output:

['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.']
['sentence one.']
['sentence four.']
answered 2010-03-02T13:14:35.927

Your Answer