参见英文答案 Python extract pattern matches8个 我正在使用python脚本在文本文件中运行行. 我想在文本文档中搜索img标记并将标记作为文本返回. 当我运行regex re.match(line)时,它返回一个_sre.SRE
我正在使用python脚本在文本文件中运行行.
我想在文本文档中搜索img标记并将标记作为文本返回.
当我运行regex 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).喜欢
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)))
消除所有Nones.