正则表达式在没有分隔符的文本中分隔URL

2024-10-04 01:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

为另一个正则表达式问题道歉!你知道吗

我有一些输入文本,但有多个网址(只有网址)在一行没有分隔符,这是毫无帮助的

https://00e9e64bac25fa94607-apidata.googleusercontent.com/download/redacted?qk=AD5uMEnaGx-JIkLyJmEF7IjjU8bQfv_hZTkH_KOeaGZySsQCmdSPZEPHHAzUaUkcDAOZghttps://console.developers.google.com/project/reducted/?authuser=1\n

这个示例只包含两个url,但可能更多。你知道吗

我正在尝试使用python将url分隔成一个列表

我尝试过搜索解决方案,也尝试过一些,但不能让这个工作完全,因为他们贪婪地消耗所有以下网址。https://stackoverflow.com/a/6883094/659346

我意识到这可能是因为https://...在url的查询部分可能是合法允许的,但在我的情况下,我愿意假设它不能,并且假设它发生时是下一个url的开始。你知道吗

我也试过(http[s]://.*?),但是不管有没有?,它要么得到整段文字,要么就是https://


Tags: https文本comurldownload网址分隔符qk
2条回答
(https?:\/\/(?:(?!https?:\/\/).)*)

试试看这个。看到了吗演示。你知道吗

https://regex101.com/r/tX2bH4/15

import re
p = re.compile(r'(https?:\/\/(?:(?!https?:\/\/).)*)')
test_str = "https://00e9e64bac25fa94607-apidata.googleusercontent.com/download/redacted?qk=AD5uMEnaGx-JIkLyJmEF7IjjU8bQfv_hZTkH_KOeaGZySsQCmdSPZEPHHAzUaUkcDAOZghttps://console.developers.google.com/project/reducted/?authuser=1\n"

re.findall(p, test_str)

您需要使用positive lookahead assertion。你知道吗

>>> s = "https://00e9e64bac25fa94607-apidata.googleusercontent.com/download/redacted?qk=AD5uMEnaGx-JIkLyJmEF7IjjU8bQfv_hZTkH_KOeaGZySsQCmdSPZEPHHAzUaUkcDAOZghttps://console.developers.google.com/project/reducted/?authuser=1\n"
>>> re.findall(r'https?://.*?(?=https?://|$|\s)', s)
['https://00e9e64bac25fa94607-apidata.googleusercontent.com/download/redacted?qk=AD5uMEnaGx-JIkLyJmEF7IjjU8bQfv_hZTkH_KOeaGZySsQCmdSPZEPHHAzUaUkcDAOZg', 'https://console.developers.google.com/project/reducted/?authuser=1']

相关问题 更多 >