Wednesday, 28 August 2013

how do i return a string from a regex match in python

how do i return a string from a regex match in python

I am running through lines in a text file using a python script. I want to
search for an img tag within the text document and return the tag as text
When i run the regex re.match(line) it returns a _sre.SRE_MATCH object.
How do i get it to return a string?
import sys
import string
import re
f = open("sample.txt", 'r' )
l = open('writetest.txt', 'w')
count = 1
for line in f:
line = line.rstrip()
imgtag = re.match(r'<img.*?>',line)
print("yo it's a {}".format(imgtag))
when run it prints:
yo it's a None
yo it's a None
yo it's a None
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e578>
yo it's a None
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e578>
yo it's a None
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e578>
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e5e0>
yo it's a None
yo it's a None

No comments:

Post a Comment