2016-11-15 41 views
1
之间获取文本

,当我读到一文中,我有这样的一些文字的行<h3 class="heading">General Purpose</h3>串,现在我想这是唯一从上面General Purpose值..Python的正则表达式两个字符串

d = re.search(re.escape('<h3 class="heading">')+"(.*?)"+re.escape('</h3>'), str(data2)) 
if d: 
    print(d.group(0)) 
+0

你能让你的问题更清楚吗?在你的问题中加入data2,并且提到你想从data2中提取什么。 – MYGz

+0

这是一个示例字符串,还是您实际上有HTML? http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags –

+0

我想你想要d.group(1)。 0是整个匹配的字符串,1是第一个加括号的组。 – roarsneer

回答

1

0组包含整个匹配;你想组1的内容:

print(d.group(1)) 

但是总体来说,使用正则表达式解析HTML是不是一个好主意(虽然实际地说,嵌套h3标签应该是相当少见)。

+0

感谢您的回复组(1)也在工作... – kattaprasanth

1
import re 

text="""<h3 class="heading">General Purpose</h3>""" 
pattern="(<.*?>)(.*)(<.*?>)" 

g=re.search(pattern,text) 
g.group(2) 

输出:

'General Purpose' 

Demo on Regex101

如果它是一个美丽的汤对象,然后它更简单,以获得的价值。你不会需要正则表达式。

from bs4 import BeautifulSoup 

text="""<h3 class="heading">General Purpose</h3>""" 
a=BeautifulSoup(text) 
print a.select('h3.heading')[0].text 

输出:

General Purpose 
+0

感谢您的答复,它最后工作 – kattaprasanth

+0

如果它已经是一个美丽的对象,那么你不必使用额外的正则表达式来提取数据。您可以使用beautifulsoup方法来提取html数据。 – MYGz

+0

@kattaprasanth:在您评论您使用的是BeautifulSoup之前,我写了我的回答。在这种情况下,请删除我的答案中的“已接受”复选标记,并将其添加到此答案中,因为它显然是更好的答案。 –

0

警告:只能在Python,而不是PCRE或JS(不支持JS回顾后)。

(?<=\<\h3 class=\"heading\"\>).*?(?=\<\/h3\>) 
+0

感谢您的更新 – kattaprasanth

相关问题