在文本文件中考虑此输入:
foo
bar
foobar
Run Code Online (Sandbox Code Playgroud)
如果我查看python API的重包,我明白如果我想匹配foo而不是foobar我明白这个代码应该这样做
import re
code = open ('play.txt').read()
print code
print re.findall('^foo$',code)
Run Code Online (Sandbox Code Playgroud)
但输出读数
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
[]
>>>
Run Code Online (Sandbox Code Playgroud)
为什么?
您需要将re.MULTILINE添加到您的标志中.
s = '''foo
bar
foobar'''
re.findall('^foo$', s, flags=re.MULTILINE)
Out[14]: ['foo']
Run Code Online (Sandbox Code Playgroud)