2015-04-03 42 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>] 
相關問題