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

发布于 2021-01-29 19:37:06

我正在使用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
关注者
0
被浏览
113
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看