我正在使用python
腳本通過文本文件中的行。 我想在文本文檔中搜索img
標籤並將標籤作爲文本返回。如何從Python中的正則表達式匹配返回一個字符串?
當我運行正則表達式re.match(line)
時,它返回一個_sre.SRE_MATCH
對象。 我如何獲得它返回一個字符串?
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))
在運行時它打印:
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
請參閱http://docs.python.org/2/library/re.html#match-objects – stalepretzel