使用正则表达式在Python中匹配文件的开始和结束
我在找Python中用于匹配文件开头和结尾的正则表达式,但总是找不到。请问我该怎么做呢?
3 个回答
1
正则表达式中的 $
符号并不是你想要的好帮手;可以看看 这个StackOverflow的回答。
2
也许你应该更清楚地表达你的问题,比如你想要做什么。话说回来,你可以把文件的内容全部读进一个字符串里,然后用正则表达式来匹配你的模式。
import re
data=open("file").read()
pat=re.compile("^.*pattern.*$",re.M|re.DOTALL)
print pat.findall(data)
其实有更好的方法可以实现你想要的,无需使用正则表达式。
20
首先,把整个文件的内容读进一个字符串里。然后,\A 只会匹配字符串的开头,而 \Z 只会匹配字符串的结尾。如果你使用 re.MULTILINE 这个选项,'^' 就会匹配字符串的开头 和 每一行的开头(也就是换行符后面的位置),而 '$' 则会匹配字符串的结尾 和 每一行的结尾(也就是换行符前面的位置)。想了解更多,可以查看 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.']