如何从python中的正则表达式匹配返回字符串? [英] How do I return a string from a regex match in python?
本文介绍了如何从python中的正则表达式匹配返回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 python
脚本遍历文本文件中的行.我想在文本文档中搜索 img
标签并将标签作为文本返回.
I am running through lines in a text file using a python
script.
I want to search for an img
tag within the text document and return the tag as text.
当我运行正则表达式 re.match(line)
时,它返回一个 _sre.SRE_MATCH
对象.我如何让它返回一个字符串?
When I run the regex re.match(line)
it returns a _sre.SRE_MATCH
object.
How do I get it to return a string?
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)))
消除所有None
.
这篇关于如何从python中的正则表达式匹配返回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文