将regex字符串与引号和href匹配

时间:2013-03-19 08:36:45

标签: python regex

我正在尝试使用正则表达式来匹配

  <a href = "something" > 

在下面的字符串中,  但是没有打印。

E = '<a> test <a href> <a href = "something" ><a href="anything">'
H = re.match('^[<a href = ]\".\" >$' , E)
print (H)

2 个答案:

答案 0 :(得分:1)

请勿使用正则表达式解析html。

以下是使用BeautifulSoup的示例:

from BeautifulSoup import BeautifulSoup, SoupStrainer


html_string = '<a> test <a href> <a href = "something" ><a href="anything">'
for link in BeautifulSoup(html_string, parseOnlyThese=SoupStrainer('a')):
    print link.get('href')

答案 1 :(得分:0)

我建议您不要使用正则表达式来解析HTML(因为有BeautifulSoup
既然你说过你不是,那就是:

>>> regex = re.compile("(<\s*a\s*href\s*=\s*\"something\"\s*>)+")
# Run findall
>>> regex.findall(string)
[u'<a href = "something" >'] # your tag