Python regex获得最接近的匹配,没有重复的内容



我需要什么

我有一个img src链接列表。下面是一个例子:

  • https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg&nocache=1
  • https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg&nocache=1
  • https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png&nocache=1

我需要得到以下结果:

studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg
studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg
studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png

我使用以下正则表达式:

studiocake.kiev.ua.*(jpeg|png|jpg)

但是它没有按我需要的方式工作。而不是我需要的结果,我得到链接像:

studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg 

我怎样才能得到我需要的结果与Python regex

您可以让贪心的.*消耗起始匹配并捕获后者。

import re
matches = re.findall(r"(?i).*b(studiocake.kiev.uaS*b(?:jpeg|png|jpg))b", s)

在regex101查看这个演示(匹配组1)或在tio.run

查看Python演示

Inside使用S*匹配除空格以外的任何数量的字符。
我进一步为忽略大小写添加了一些b单词边界和(?i)标志。

您想要实现的是对url的标准操作,python有很多库可以实现这一目标。在这个练习中,我建议使用url解析库,而不是使用正则表达式,它提供了标准的操作,并提供了更好的代码。

from urllib.parse import urlparse, parse_qs

def extractSrc(strUrl):
# Parse original URL using urllib
parsed_url = urlparse(strUrl)
# Find the value of query parameter img
src_value = parse_qs(parsed_url.query)['src'][0]

# Again, using same library, parse img url which we got above.
img_parsed_url = urlparse(src_value)
# Remove the scheme in the img URL and return result.
scheme = "%s://" % img_parsed_url.scheme
return img_parsed_url.geturl().replace(scheme, '', 1)

urls = '''https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg&nocache=1
https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg&nocache=1
https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png&nocache=1'''
for u in urls.split('n'):
print(extractSrc(u))

输出:

studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg
studiocake.kiev.ua/wp-content/uploads/IMG_4945-333x444.jpeg
studiocake.kiev.ua/wp-content/uploads/tri-shokolada.png

Myhack表达式是这样的:

(https://)(studiocake.kiev.ua.*(php)?src=https://)(studiocake.kiev.ua.*(jpeg|png|jpg))(&nocache=1)

$4

代替解释…

我刚刚选择了parts中的所有链接然后将其替换为所需的特定部分。

最新更新