Match start and end of file in python with regex

It's hard for me to find a regex for the start and end of a file in python. How to do it?

+5
source share
3 answers

Read the entire file in line, then \ A matches only the beginning of the line, and \ Z matches only the end of the line. With re.MULTILINE '^' corresponds to the start line and just after the new line, and "$" matches the end of line and 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.']
+10
source

, , , . , re.

import re
data=open("file").read()
pat=re.compile("^.*pattern.*$",re.M|re.DOTALL)
print pat.findall(data)

, , , re.

+2

regex is $ NOT your friend; see this answer SO

0
source

All Articles