我希望用户提交一个有效但也是图像的 URL,以 .jpg、.png 或 .gif 结尾。
14 回答
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png) )(?:\?([^#]*))?(?:#(.*))?
这是来自RFC 2396的官方 URI 解析正则表达式的(稍作修改)版本。它允许#fragments
并?querystrings
出现在文件名之后,这可能是也可能不是您想要的。它还匹配任何有效域,包括localhost
,这可能不是您想要的,但可以修改。
一个更传统的正则表达式可能如下所示。
^https?://(?:[a-z0-9\-]+\.)+[az]{2,6}(?:/[^/#?]+)+\.(?:jpg |gif|png)$ |-------- 域 -----------|--- 路径 ---|-- 扩展名 ---|
编辑见我的另一条评论,虽然它没有像这个一样完整地回答这个问题,但我觉得在这种情况下它可能更有用。但是,我把它留在这里业力嫖娼完整性原因。
实际上。
你为什么要检查网址?这不能保证你会得到一个图像,也不能保证你拒绝的东西不是图像。尝试对其执行 HEAD 请求,并查看它实际上是什么内容类型。
通常,您最好使用内置库或框架函数验证 URL,而不是滚动您自己的正则表达式来执行此操作 - 有关详细信息,请参阅检查字符串是否为有效 URL 的最佳正则表达式是什么。
但是,如果您热衷于这样做,请查看以下问题:
然后,一旦您对 URL 感到满意(通过您用来验证它的任何方式),您可以使用简单的“endswith”类型字符串运算符来检查扩展名,或者使用简单的正则表达式,如
(?i)\.(jpg|png|gif)$
(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png)
这将处理来自该字符串的所有图像:
background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto;
<div id="divbg" style="background-color:#ff0000"><img id="bg" src="../res/img/temp/634043/original/cc3d8715eed0c.jpg" width="100%" height="100%" /></div>
background-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png);
background: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3 _d8715eed0c.jpg) repeat fixed left top; cursor: auto;
background: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto;
在此处测试您的正则表达式:https ://regex101.com/r/l2Zt7S/1
(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png)
对我来说真的很好。
这将匹配以下形式的 URL:
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png
在此处针对 URL 检查此正则表达式:http ://regexr.com/3g1v7
如果您真的想确定,获取给定 URL 的前一两个千字节应该足以确定您需要了解的有关图像的所有信息。
这是一个如何使用 Python获取该信息的示例,这是一个将其用作 Django 表单字段的示例,它允许您根据其 URL 轻松验证图像的存在、文件大小、尺寸和格式。
这是 Perl 的基本思想。盐调味。
#!/usr/bin/perl 使用 LWP::UserAgent; 我的 $ua = LWP::UserAgent->new; @ARGV = qw(http://www.example.com/logo.png); 我的 $response = $ua->head($ARGV[0]); 我的($class, $type) = 拆分 m|/|, lc $response->content_type; print "这是一张图片!\n" if $class eq 'image';
如果您需要检查 URL,请为其使用可靠的库,而不是尝试自己处理所有奇怪的情况:
使用 URI; 我的 $uri = URI->new($ARGV[0]); 我的 $last = ( $uri->path_segments )[-1]; 我的( $extension ) = $last =~ m/\.([^.]+)$/g; print "我的扩展名是 $extension\n";
祝你好运, :)
使用FastImage - 它会从 URL 中获取所需的最少数据,以确定它是否是图像、图像的类型和大小。
^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))
除了丹的答案。
如果有IP地址而不是域。
稍微改变一下正则表达式。(有效 IPv4 和 IPv6 的临时解决方案)
^https?://(?:[a-z0-9\-]+\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$
但是,这可以改进,以便 IPv4 和 IPv6 验证子网范围。
此表达式将匹配所有图像 url -
^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$
例子 -
有效的 -
https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png
http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg
example.com/de_home_teaser-box_puzzle_in_the_sun.png
www.example.com/de_home_teaser-box_puzzle_in_the_sun.png
https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg
http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg
https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg
无效的 -
https://www.example.com
http://www.example.com
www.example.com
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2
http://www.siteabcd.com:8008
只是提供更好的解决方案。您可以验证 uri 并检查格式然后:
public class IsImageUriValid
{
private readonly string[] _supportedImageFormats =
{
".jpg",
".gif",
".png"
};
public bool IsValid(string uri)
{
var isUriWellFormed = Uri.IsWellFormedUriString(uri, UriKind.Absolute);
return isUriWellFormed && IsSupportedFormat(uri);
}
private bool IsSupportedFormat(string uri) => _supportedImageFormats.Any(supportedImageExtension => uri.EndsWith(supportedImageExtension));
}
const url = "https://www.laoz.com/image.png";
const acceptedImage = [".png", ".jpg", ".gif"];
const extension = url.substring(url.lastIndexOf("."));
const isValidImage = acceptedImage.find((m) => m === extension) != null;
console.log("isValidImage", isValidImage);
console.log("extension", extension);
Reference: See DecodeConfig section on the official go lang image lib docs here
I believe you could also use DecodeConfig to get the format of an image which you could then validate against const types like jpeg, png, jpg and gif ie
import (
"encoding/base64"
"fmt"
"image"
"log"
"strings"
"net/http"
// Package image/jpeg is not used explicitly in the code below,
// but is imported for its initialization side-effect, which allows
// image.Decode to understand JPEG formatted images. Uncomment these
// two lines to also understand GIF and PNG images:
// _ "image/gif"
// _ "image/png"
_ "image/jpeg"
)
func main() {
resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
data, _, err := image.Decode(resp.Body)
if err != nil {
log.Fatal(err)
}
reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
config, format, err := image.DecodeConfig(reader)
if err != nil {
log.Fatal(err)
}
fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format)
}
format here is a string that states the file format eg jpg, png etc