Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match start and end of file in python with regex

Tags:

python

regex

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

like image 980
zlack Avatar asked Mar 02 '10 10:03

zlack


2 Answers

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.']
like image 101
Mark Tolonen Avatar answered Oct 24 '22 12:10

Mark Tolonen


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.

like image 42
ghostdog74 Avatar answered Oct 24 '22 12:10

ghostdog74