使用正则表达式匹配python中文件的开始和结束

zla*_*ack 7 python regex

我很难在python中找到文件开头和结尾的正则表达式.我怎么做到这一点?

Mar*_*nen 14

将整个文件读入字符串,然后\ A仅匹配字符串的开头,\ Z仅匹配字符串的结尾.使用re.MULTILINE,'^'匹配字符串的开头刚刚在换行符之后,'$'匹配字符串的结尾并且在换行符之前.有关re语法,请参阅Python文档.

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)
Run Code Online (Sandbox Code Playgroud)

输出:

['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.']
['sentence one.']
['sentence four.']
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 2

也许你应该更清楚地提出你的问题,比如你想要做什么。也就是说,您可以将文件合并为一个完整的字符串,并使用 re 匹配您的模式。

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

有更好的方法可以做你想做的事,无论它是什么,而无需重复。

  • 任何。这不是一个完整的解决方案,因为我们不确定 OP 真正想要做什么。我能做的最好的事情就是告诉他他可以将整个文件作为字符串读取,并像普通字符串一样对其进行正则表达式。 (2认同)