I'm having a hard time finding the regex for the start and end of a file in python. How would I accomplish this ?
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.']
Maybe you should pose your question more clearly, like what you trying to do. That said, you can slurp the file into one whole string, and match your pattern using re.
import re
data=open("file").read()
pat=re.compile("^.*pattern.*$",re.M|re.DOTALL)
print pat.findall(data)
There are better ways to do what you want, whatever it is, without re.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With