[英]Regex to find all URLs in a string that contains a substring AND don't contain another
我設法從這個字符串中過濾掉所有的 URL:
hi, this is your link (but this one is bad formatted and useless):
https://www.test.comhttps://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
but there is a good link too:
https://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
and there are also other irrelevant links:
http://www.google.com
http://test.test.com
使用這個正則表達式
http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+
在玩了一段時間后,我一直在試圖理解如何調整它並只得到:
https://www.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
過濾掉包含“/next”的 URL 的最簡單方法是什么? 但不是'comhttps'?
謝謝一堆!
這樣的事情怎么辦?
(https?:\/\/[a-z0-9]+(?:[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})(?=https?)(\S+)
我們將使用i
標志進行不區分大小寫的搜索。
在這里測試: https : //regex101.com/r/J62XZq/2
https?:\\/\\/
是尋找http://或https://
[a-z0-9]+(?:[\\-\\.]{1}[a-z0-9]+)*\\.[az]{2,6}
是尋找有效的域名。 我沒有檢查它是否真的完全防彈。 不過好像還不錯。 我們也許可以找到一個官方的正則表達式來驗證域名。 (?:)
組是一個非捕獲組(如果我們不需要它)。
(https?:\\/\\/[a-z0-9]+(?:[\\-\\.]{1}[a-z0-9]+)*\\.[az]{2,6})
是一起並在一個組中捕獲,以便我們擁有原始 URL。
(?=https?)
是正向前瞻,因此之前的域必須跟在 http 或 https 之后。 如果您可以使用 ftp 或其他協議,則可能需要對其進行調整。
(\\S+)
是將非空格匹配一次或多次並將其捕獲在一組中(供以后使用和處理。必須處理第二組以擺脫第二個查詢字符串?param=x&option
其中可能屬於周圍的 URL。
由於我們討論了只匹配正確的答案,這意味着我的答案並不是真正的好答案。 理解必須做什么並不總是那么容易。
https://regex101.com/r/J62XZq/7
在這里,我們尋找域名后面沒有http:
或https:
。
訣竅是在開頭添加\\b
以避免匹配 URL 內的 URL 並在域之后使用負前瞻。
\bhttps?:\/\/[a-z0-9]+(?:[\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(?!https?:)\/\S+\/next\?(\S+)
負前瞻是用(?!https?:)
(我沒有添加雙斜杠,因為我認為它已經足夠了)。
帶有/next
的最后一部分可能不是必需的。 這取決於您是否想將 URL 與內部特定匹配。
用:
\bhttps?://(?=[\w.]*/)(?:(?!https?://).)*
它會找到正確的 url 並拒絕您示例中的其他 url。
import re
body_text = '''
hi, this is your link (but this one is bad formatted and useless):
https://www.test.comhttps://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
but there is a good link too:
https://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2
and there are also other irrelevant links:
http://www.google.com
http://test.test.com
'''
url = re.findall(r"\bhttps?://(?=[\w.]*/)(?:(?!https?://).)*", body_text)
print url
輸出:
['https://app.test.com/a/b/c/5e20bed422e7880012ba8acc/next?param=1?locale=2']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.