2011-12-20 45 views
2

我需要在Python中使用正則表達式的幫助。使用REGEX提取模式之間的文本

我有一個大的HTML文件[大約400線]具有下列模式

text here(div,span,img tags) 

<!-- 3GP||Link|| --> 

text here(div,span,img tags) 

所以,現在我正在尋找一個正則表達式,可以提取我這個 - :

Link 

給定的模式在html文件中是唯一的。

回答

4
>>> d = """ 
... Some text here(div,span,img tags) 
... 
... <!-- 3GP||**Some link**|| --> 
... 
... Some text here(div,span,img tags) 
... """ 
>>> import re 
>>> re.findall(r'\<!-- 3GP\|\|([^|]+)\|\| --\>',d) 
['**Some link**'] 
  • r''是原始文字,它停止標準的字符串的解釋逃脫
  • \<!-- 3GP\|\|是一個正則表達式逃脫匹配<!-- 3GP||
  • ([^|]+)將匹配所有字符都一個|和團體也爲了方便
  • \|\| --\>|| -->
  • 一個正則表達式匹配逃脫re.findall返回字符串中重新組織模式的所有非重疊匹配,如果在重新組合模式中存在組表達式,則返回該匹配。
+0

Thanks.It工作。如果你不介意,你可以向我解釋你在那裏做了什麼。 – RanRag 2011-12-20 12:03:29

+0

我覺得嚴格說來了''<' and '>這裏不需要逃跑,但它不會做任何傷害,他們是在其它模式實現的元字符。 – MattH 2011-12-20 12:22:41

+0

謝謝。一個非常好的解釋。可以給我建議學習正則表達式的好教程。問題是有太多的教程可用。 – RanRag 2011-12-20 12:59:32

0
import re 
re.match(r"<!-- 3GP\|\|(.+?)\|\| -->", "<!-- 3GP||Link|| -->").group(1) 

產生"Link"

0

如果您需要解析別的東西,你也可以用BeautifulSoup結合正則表達式:

import re 
from BeautifulSoup import BeautifulSoup, Comment 

soup = BeautifulSoup(<your html here>) 
link_regex = re.compile('\s+3GP\|\|(.*)\|\|\s+') 
comment = soup.find(text=lambda text: isinstance(text, Comment) 
        and link_regex.match(text)) 
link = link_regex.match(comment).group(1) 
print link 

注意,在這種情況下,正規表示法只需要因爲BeautifulSoup已經細心地匹配發言內容從評論中提取文本。

+0

我的HTML過於畸形的,這就是爲什麼我不使用美麗的湯。 – RanRag 2011-12-20 12:52:33

+0

我明白了,那麼我同意,最好的選擇是[淨化你的數據(http://www.crummy.com/software/BeautifulSoup/documentation.html#Sanitizing%20Bad%20Data%20with%使用正則表達式20Regexps)。 – jcollado 2011-12-20 12:56:17

+0

是的,那會怎麼做 – RanRag 2011-12-20 13:01:26

相關問題