繁体   English   中英

用于查找字符串中所有图像 url 的正则表达式

[英]Regular expression to find all the image urls in a string

我正在尝试构建一个正则表达式,从字符串中查找所有图像 url。 图片 url 可以是绝对路径也可以是相对路径。

所有这些都应该是有效的匹配项:

 ../example/test.png
   
 https://www.test.com/abc.jpg
   
 images/test.webp

例如:如果我们定义

inputString="img src=https://www.test.com/abc.jpg background:../example/test.png <div> images/test.webp image.pnghello"

那么我们应该找到这 3 个匹配项:

https://www.test.com/abc.jpg
../example/test.png
images/test.webp

我目前正在这样做(我正在使用 python),它只找到绝对路径,只找到一些图像,有时也有错误的匹配(找到一个字符串,里面有一个图像 url,但添加了很多东西是在图片网址之后)

imageurls = re.findall(r'(?:"|\')((?:https?://|/)\S+\.(?:jpg|png|gif|jpeg|webp))(?:"|\')', inputString)

你可以试试:

(?i)https?\S+(?:jpg|png|webp)\b|[^:<>\s\'\"]+(?:jpg|png|webp)\b

正则表达式演示。


import re

s = '''img src=https://www.test.com/abc.jpg background:../example/test.png <div> images/test.webp image.pnghellobackground-image: url('../images/pics/mobile/img.JPG')'''
pat = re.compile(r'(?i)https?\S+(?:jpg|png|webp)\b|[^:<>\s\'\"]+(?:jpg|png|webp)\b')

for m in pat.findall(s):
    print(m)

印刷:

https://www.test.com/abc.jpg
../example/test.png
images/test.webp
../images/pics/mobile/img.JPG

你对那个怎么想的:

re.findall(r'(?=:[^\S])?(?:https?://)?[\./]*[\w/\.]+\.(?:jpg|png|gif|jpeg|webp)', inputString)

和:

"img src=http://another.org/hola.gif https://www.test.com/abc.jpg background:../example/test.png <div> images/test.webp image.pnghello"

给出:

 ['http://another.org/hola.gif',
 'https://www.test.com/abc.jpg',
 '../example/test.png',
 'images/test.webp',
 'image.png']

这可能需要更多的测试样本:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM