【发布时间】:2010-03-02 10:37:57
【问题描述】:
我很难在 python 中找到文件开头和结尾的正则表达式。 我将如何做到这一点?
【问题讨论】:
-
正则表达式应用于字符串,而不是文件。
我很难在 python 中找到文件开头和结尾的正则表达式。 我将如何做到这一点?
【问题讨论】:
将整个文件读入字符串,则\A只匹配字符串的开头,\Z只匹配字符串的结尾。使用 re.MULTILINE,'^' 匹配字符串的开头 和 就在换行符之后,而 '$' 匹配字符串的结尾 and 就在换行符之前.请参阅re syntax 的 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)
输出:
['sentence one.', 'sentence two.', 'sentence three.', 'sentence four.']
['sentence one.']
['sentence four.']
【讨论】:
也许你应该更清楚地提出你的问题,比如你想做什么。也就是说,您可以将文件 slurp 成一个完整的字符串,并使用 re 匹配您的模式。
import re
data=open("file").read()
pat=re.compile("^.*pattern.*$",re.M|re.DOTALL)
print pat.findall(data)
有更好的方法来做你想做的事,不管它是什么,而无需重新。
【讨论】:
regex $ 是不是你的朋友;见this SO answer
【讨论】: