在文本文件中考虑此输入:
foo
bar
foobar
如果我查看in python API重新打包,我了解如果我想匹配foo
而不是foobar
,我了解此代码应该这样做
import re
code = open ('play.txt').read()
print code
print re.findall('^foo$',code)
然而输出读取
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import play
foo
bar
foobar
[]
>>>
为什么?
答案 0 :(得分:7)
您需要在标记中添加re.MULTILINE。
s = '''foo
bar
foobar'''
re.findall('^foo$', s, flags=re.MULTILINE)
Out[14]: ['foo']