【问题标题】:Filter urls by last path with regex使用正则表达式按最后一个路径过滤 url
【发布时间】:2021-07-12 22:46:36
【问题描述】:

我需要使用正则表达式过滤所有最后路径的 url,除了应该跳过的几个路径。例如:

import re

urls_to_exclude = ["example_1", "example_2", "example_3"]

url_1 = "htttps://site.com/api/user/endpath"
url_2 = "htttps://site.com/api/user/other_end?limit=10"
url_3 = "htttps://site.com/api/customer/example_1#tag"
url_4 = "htttps://site.com/api/blog/example_2"

>>> match = re.findall(r"...magic_regex...", url_1)
>>> 'endpath'

>>> match = re.findall(r"...magic_regex...", url_2)
>>> 'other_end'

>>> match = re.findall(r"...magic_regex...", url_3)
>>> 'example_1'

>>> match = re.findall(r"...magic_regex...", url_4)
>>> 'example_2'

它应该是编译对象的正则表达式字符串。 谢谢

【问题讨论】:

  • 只需用/ 拆分网址,取最后一个元素(array[-1])并使用in 运算符。真的不需要正则表达式。此外,还不清楚你想用这些网址做什么。
  • urllib.parse.urlparse 将负责将?foo=bar#whatever 从路径中分离出来,正如@Jan 所说,您可以使用'/' 进行拆分,但我更喜欢使用posixpath.basename。为什么坚持使用正则表达式?我的意思是,可以做到,但我更喜欢更简单/更清晰的解决方案。

标签: python regex string url filtering


【解决方案1】:

您可以尝试正则表达式,它不会为您提供确切的最后路径,但您可以使用result[1:-1] 轻松评估

正则表达式: /[\w\d_-]+[?^"#]

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2021-07-29
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多