2015-10-13 261 views
-6

我有以下字符串,我想在這種情況下,應當認可正則表達式字符串在python

而且有時輸入,可就是這樣,提取現場

<td class="label" width="150"">State</td><td width="" class="field">Approved&nbsp;</td> 

的價值

<td class="label" width="150"">Type</td><td width="" class="field">Technical&nbsp;Document&nbsp;</td> 

這在技術SHD結果文檔

有時也可以是

<td class="label" width="150"">Title</td><td width="" class="field">Reversal Plate</td> 

在這種情況下,它會反向板

我們怎麼能寫這樣的字符串正則表達式。

+3

你看起來像你正試圖用正則表達式解析HTML。你想要更好的選擇嗎? –

回答

1

不要使用正則表達式,你應該使用一些HTML/XML解析器,例如BeautifulSoup

from bs4 import BeautifulSoup 
soup = BeautifulSoup(s,'html.parser') #`s` being your string. 
for td in soup.findAll('td',class_="field"): 
    print(td.get_text()) 

以上將爲您的例子得到正確的結果。

演示 -

>>> s = """<td class="label" width="150"">State</td><td width="" class="field">Approved&nbsp;</td>""" 
>>> from bs4 import BeautifulSoup 
>>> soup = BeautifulSoup(s,'html.parser') 
>>> for td in soup.findAll('td',class_="field"): 
...  print(td.get_text()) 
... 
Approved  
>>> s = """<td class="label" width="150"">Type</td><td width="" class="field">Technical&nbsp;Document&nbsp;</td>""" 
>>> soup = BeautifulSoup(s,'html.parser') 
>>> for td in soup.findAll('td',class_="field"): 
...  print(td.get_text()) 
... 
Technical Document  
+0

我想嘗試一下可用的選項,是否有可能使用正則表達式? –

+0

@RidhiJain你可以看看另一個答案,但請注意它只能在非常特定的情況下工作。所以如果你100%肯定你給出的三個例子是你想找到的唯一案例,那麼你可以使用它。它會停止工作,如果在標籤中有''''和'>'之間有一個小的窗口,但是大多數正則表達式解決方案你會得到這樣的結果 –

+0

如何安裝美麗的湯.... IM新到Python ,如何檢查運行 –

0

正如@Anand小號庫馬爾提到你不必使用regex,使用Beautifulsoup更快。不過,既然你問了regex解決方案,可以使用下面的代碼:

import re 
s = '<td class="label" width="150"">State</td><td width="" class="field">Approved&nbsp;</td>' 
m = re.compile('"field">(.*)<') 
print (m.search(s).group(1)) 

輸出:

Approved&nbsp; 

regex解決方案將匹配任何裏面的class="field">....</td>