简体   繁体   中英

matching a whole line in python regex

Consider this input in a text file:

foo
bar
foobar

If I look in python API for the re package I understand that if I want to match the foo and not the foobar I understand that this code should do it

import re

code = open ('play.txt').read()
print code

print re.findall('^foo$',code)

However the output reads

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

[]
>>> 

Why?

You need to add re.MULTILINE to your flags.

s = '''foo
bar
foobar'''
re.findall('^foo$', s, flags=re.MULTILINE)

Out[14]: ['foo']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM