Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matching a whole line in python regex

Tags:

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?

like image 586
Yotam Avatar asked Jan 24 '26 14:01

Yotam


1 Answers

You need to add re.MULTILINE to your flags.

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

Out[14]: ['foo']
like image 118
Harvey Avatar answered Jan 27 '26 03:01

Harvey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!