【问题标题】:How to use re.match to find the first part of an URL?如何使用 re.match 查找 URL 的第一部分?
【发布时间】:2019-08-17 00:04:15
【问题描述】:

我正在使用“urllib.request.urlopen(URL)”来查找不同服务器上不同文件的大小。问题是我需要对自己进行身份验证。我通过以下方式做到这一点。

url = "https://abc123-abca93.xxx.xxxx.se/other_parts_of_url/file.tar"
top_level_url = "https://abc123-abca93.xxx.xxxx.se/"
password_mgr.add_password(None, top_level_url, 'username',password.get())
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

这样我现在可以在访问文件时访问该文件

filesize = urllib.requests.urlopen(url).headers._headers[8][1]

但问题是每个文件的URL都会改变所以我想使用RegExp找到URL的第一部分,即

"https://"+more_characters+".se"+possibly_port_number+"/"

我在想我可以使用 re.match,但我不确定如何为这种情况编写正确的逻辑,是否可以做类似的事情

match = re.match("https://" + any amount of characters +"/", url)

【问题讨论】:

  • 您好,您能告诉我为什么要使用正则表达式,而您可以拆分字符串并进行比较吗?
  • 好吧,我想我也可以使用 split ,感觉正则表达式会提供更紧凑的解决方案。如果我要使用 split 我会做类似 "a = url.split("/") " 的事情,我将不得不查找包含 ".se" 字符串的索引,然后将字符串放在一起替换 " " 的每个实例由于拆分,带有“/”。似乎有点乏味。
  • 假设所有主机都属于.se顶级域,如果您仍想使用正则表达式,这个可以提供帮助:r'^.*:[/]{2}(.*\.se)[:/].*$'

标签: python regex match


【解决方案1】:

您也可以使用普通的旧 str.split()

Python 3.7.2 (default, Mar 21 2019, 10:05:02) 
[GCC 9.0.1 20190227 (Red Hat 9.0.1-0.8)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 'https://abc123-abca93.xxx.xxxx.se/other_parts_/file.tar'.split('/')
['https:', '', 'abc123-abca93.xxx.xxxx.se', 'other_parts_', 'file.tar']
>>> 

【讨论】:

    【解决方案2】:

    这是一个常见问题,请使用URLParse (python3 version)

    from urllib.parse import urlparse
    o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
    toplevel = o.scheme + "://" + o.netloc
    

    【讨论】:

      【解决方案3】:

      您可以使用urllib 的解析功能:

      from urllib.parse import urlparse
      
      url = "https://abc123-abca93.xxx.xxxx.se/other_parts_of_url/file.tar"
      
      parse_result = urlparse(url)
      
      top_level_url = parse_result.netloc
      

      【讨论】:

      【解决方案4】:

      可能的正则表达式: https://regex101.com/r/GyEFx2/1

      然后使用:

      match = re.match(pattern, url)
      if match:
          first_part = match.group(0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        • 2016-07-02
        • 1970-01-01
        • 2011-08-17
        相关资源
        最近更新 更多