2015-04-03 74 views
0

我需要一个正则表达式来匹配空间或没有任何东西。我使用它来查找包含HTML代码的字符串中的类。现在python正则表达式匹配空间或什么也没有

我的模式如下:

pattern = r'class="([A-Za-z0-9_\./\\-]*)"' 

不过,这并不赶上 的“类=‘一些类名’”感谢你的帮助。谢谢。

+1

加上'\ S *'。我会建议使用一个专用的解析器,如beautifulsoup :) – HamZa 2015-04-03 11:17:55

+0

可以使用'class =([''])(。*?)\ 1“'来匹配你想要的正则表达式,但是......嘘...... :) – 2015-04-03 11:40:54

回答

2

最好使用HTML解析器,BeautifulSoup

from bs4 import BeautifulSoup 
soup = BeautifulSoup(url) 
print soup.find_all(tag_name, class_name) 

演示:

>>> html_doc = """ 
<html><head><title>The Dormouse's story</title></head> 

<p class="title"><b>The Dormouse's story</b></p> 

<p class="story">Once upon a time there were three little sisters; and their names were 
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, 
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and 
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; 
and they lived at the bottom of a well.</p> 

<p class="story">...</p> 
""" 
>>> soup = BeautifulSoup(html_doc) 
>>> soup.find_all('p', 'title') 
[<p class="title"><b>The Dormouse's story</b></p>] 
>>> soup.find_all('a') 
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]