[英]Regex to find strings containing substring, but not ending on same substring
[英]Regex to extract substring between different starting and ending strings within HTML
我正在嘗試編寫一個簡單的抓取工具,可以從網頁中提取特定的 URL。 該頁面有許多 URL,但我想獲得以一組特定字符結尾的 URL。
例如,如果頁面源代碼中的某處有一個如下所示的 url:
source: "https://www.website.com/dog.pdf"
我想不帶引號返回https://www.website.com/dog.pdf
。 如果有多個匹配項,我只想返回第一個。
所以正則表達式應該在source:
之后提取所有內容source:
直到並包括.pdf"
——
我看過其他問題,但大多數答案都拒絕提供正則表達式,而是說使用startswith()
和endswith()
。 但是由於頁面源可能很大,我擔心性能。 不過,我是 Python 新手,也許我只是不了解如何使用這些方法。
干得好
import re
example = '''
source: "https://www.website.com/dog.pdf"
source: "https://www.website.com/cat.pdf"
'''
pattern = r'"(?P<url>.+?)"'
m = re.search(pattern, example)
url = m.group('url') # result is https://www.website.com/dog.pdf
更新。
要返回雙引號中的第一個鏈接,正則表達式將如下所示:
pattern = r'"(?P<url>https?:\/\/.+?)"'
如果您需要在以.pdf
結尾的雙引號中找到第一個鏈接,則正則表達式將如下所示:
pattern = r'"(?P<url>https?:\/\/.+?\.pdf)"'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.