代码之家  ›  专栏  ›  技术社区  ›  Jim

Regex检查以.jpg、.png或.gif结尾的有效URL

  •  30
  • Jim  · 技术社区  · 17 年前

    11 回复  |  直到 17 年前
        1
  •  76
  •   Community Mohan Dere    9 年前
    (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?

    这是来自的官方URI解析regexp的(稍加修改)版本 RFC 2396 . 它允许 #fragments ?querystrings 显示在文件名之后,文件名可能是您想要的,也可能不是您想要的。它还匹配任何有效域,包括 localhost

    更传统的regexp可能如下所示。

    ^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$
              |-------- domain -----------|--- path ---|-- extension ---|

    看我的 other comment ,虽然它没有回答这个问题那么完整,但我觉得在这种情况下它可能更有用。不过,我要把这个留给你

        2
  •  38
  •   Dan Aditi    17 年前

    事实上

    你为什么要检查网址?这不能保证你得到的是一个形象,也不能保证你拒绝的东西 不是 图像。尝试对其执行HEAD请求,并查看其内容类型 是

        3
  •  17
  •   Community Mohan Dere    9 年前

    通常,最好使用内置库或框架函数验证URL,而不是使用自己的正则表达式来验证—请参阅 What is the best regular expression to check if a string is a valid URL 详情请参阅。

    但是,如果您热衷于这样做,请查看以下问题:

    Getting parts of a URL (Regex)

    (?i)\.(jpg|png|gif)$
    
        4
  •  14
  •   Adam Naylor    9 年前
    (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

        5
  •  4
  •   Blairg23 jfs    9 年前

    (http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png) 对我来说真的很好。

    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

        6
  •  2
  •   brian d foy    17 年前

    #!/usr/bin/perl
    
    use LWP::UserAgent;
    
    my $ua = LWP::UserAgent->new;
    
    @ARGV = qw(http://www.example.com/logo.png);
    
    my $response = $ua->head( $ARGV[0] );
    
    my( $class, $type ) = split m|/|, lc $response->content_type;
    
    print "It's an image!\n" if $class eq 'image';
    

    如果需要检查URL,请使用可靠的库,而不是自己尝试处理所有奇怪的情况:

    use URI;
    
    my $uri = URI->new( $ARGV[0] );
    
    my $last = ( $uri->path_segments )[-1];
    
    my( $extension ) = $last =~ m/\.([^.]+)$/g;
    
    print "My extension is $extension\n";
    

    祝你好运,:)

        7
  •  2
  •   Jonny Buchanan    17 年前

    真正地 要确定,获取给定URL的前一两个KB应该足以确定您需要了解的有关图像的所有信息。

    这是 an example of how you can get that information an example of it being put to use, as a Django form field 它允许您根据图像的URL轻松验证图像的存在性、文件大小、尺寸和格式。

        8
  •  0
  •   dkam    15 年前
        9
  •  0
  •   Community Mohan Dere    6 年前

    增加 Dan's

    如果存在IP地址而不是域。

    ^https?://(?:[a-z0-9\-]+\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$
    

    但是,对于IPv4和IPv6来说,这是可以改进的,以验证子网范围。

        10
  •  0
  •   d-_-b    11 年前
    ^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))
    
        11
  •  0
  •   Tushar Walzade    8 年前

    ^(?: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
    
        12
  •  0
  •   kevthanewversi    7 年前

    参考:参见官方go-lang图像库文档的DecodeConfig部分 here

    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)
    }
    

    这里的格式是一个字符串,表示文件格式,如jpg、png等

        13
  •  0
  •   Quico Llinares Llorens    5 年前

    只是提供了一个更好的解决方案。您只需验证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));
    }
    
        14
  •  0
  •   momoSakhoMano    5 年前
        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);