2013-08-28 22 views
31

我正在使用python腳本通過文本文件中的行。 我想在文本文檔中搜索img標籤並將標籤作爲文本返回。如何從Python中的正則表達式匹配返回一個字符串?

當我運行正則表達式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 

回答

40

您應該使用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秒。

+0

請參閱http://docs.python.org/2/library/re.html#match-objects – stalepretzel

6

考慮到可能有幾個img標籤,我會建議re.findall

import re 

with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out: 
    for line in f_in: 
     for img in re.findall('<img[^>]+>', line): 
      print >> f_out, "yo it's a {}".format(img) 
1

注意re.match(pattern, string, flags=0)只返回在比賽開始的字符串。如果要在字符串中的任意位置找到匹配的任何地方,請改爲使用re.search(pattern, string, flags=0)https://docs.python.org/3/library/re.html)。這將掃描字符串並返回第一個匹配對象。然後你可以按照人們的建議提取匹配的字符串match_object.group(0)

相關問題