我正在使用python脚本遍历文本文件中的行。我想img在文本文档中搜索标签,然后将标签作为文本返回。
python
img
当我运行正则表达式时,re.match(line)它将返回一个 _sre.SRE_MATCH对象。如何获取返回的字符串?
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
您应该使用re.MatchObject.group(0)。喜欢
re.MatchObject.group(0)
imtag = re.match(r'<img.*?>', line).group(0)
编辑:
您最好做一些类似的事情
imgtag = re.match(r'<img.*?>',line) if imtag: print("yo it's a {}".format(imgtag.group(0)))
消除所有None的。
None