【发布时间】: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