小编典典

如何从python中的正则表达式匹配返回字符串?

python

我正在使用python脚本遍历文本文件中的行。我想img在文本文档中搜索标签,然后将标签作为文本返回。

当我运行正则表达式时,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

阅读 227

收藏
2020-12-20

共1个答案

小编典典

您应该使用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的。

2020-12-20