[英]Extract text between pattern using REGEX
我需要python中的正則表達式幫助。
我有一個大的html文件[大約400行],具有以下模式
text here(div,span,img tags)
<!-- 3GP||Link|| -->
text here(div,span,img tags)
所以,現在我正在尋找一個可以提取我的正則表達式:
Link
給定的模式在html文件中是唯一的。
>>> 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
返回字符串中re模式的所有非重疊匹配,如果re模式中有一個組表達式,則返回該表達式。 import re
re.match(r"<!-- 3GP\|\|(.+?)\|\| -->", "<!-- 3GP||Link|| -->").group(1)
產生"Link"
。
如果需要解析其他內容,還可以將正則表達式與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已經負責從注釋中提取文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.