Jim
Jim

Reputation:

Regex to check if valid URL that ends in .jpg, .png, or .gif

I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.

Upvotes: 41

Views: 141561

Answers (15)

brian d foy
brian d foy

Reputation: 132920

Here's the basic idea in Perl. Fetch the URL and see what it says in the Content-type header:

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = "http://www.example.com/logo.png";

my $response = $ua->head( $url );

my( $class, $type ) = split m|/|, lc $response->content_type;

print "It's an image!\n" if $class eq 'image';

If you need to inspect just the URL without accessing it, use a solid library for it rather than trying to handle all the odd situations yourself:

use URI;

my $url = "http://www.example.com/logo.png";
my $uri = URI->new( $url );

my $last = ( $uri->path_segments )[-1];

my( $extension ) = $last =~ m/\.([^.]+)$/g;

print "My extension is $extension\n";

And here's a Mojolicious example:

use Mojo::URL;

my $url = "http://www.example.com/logo.png";
my( $extension ) = 
    Mojo::URL->new($url)->path->parts->[-1] =~ m/\.([^.]+)$/g;

print "My extension is $extension\n";

Good luck, :)

Upvotes: 2

Sasikumar
Sasikumar

Reputation: 898

I am working in Javascript based library (React). The below regex is working for me for the URL with image extension.

[^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$

Working URL`s are:

https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg https://images.pexels.com/photos/674010/pexels-photo-674010.jpg https://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG http://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG images.pexels.com/photos/674010/pexels-photo-674010.JPEG

Got the solution from: https://www.geeksforgeeks.org/how-to-validate-image-file-extension-using-regular-expression/

Upvotes: 1

momoSakhoMano
momoSakhoMano

Reputation: 77

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

Upvotes: 0

Quico Llinares Llorens
Quico Llinares Llorens

Reputation: 237

Just providing a better solution. You can just validate the uri and check the format then:

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

Upvotes: 0

kevthanewversi
kevthanewversi

Reputation: 3756

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

Upvotes: 0

Tushar Walzade
Tushar Walzade

Reputation: 3819

This expression will match all the image urls -

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$

Examples -

Valid -

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

Invalid -

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

Upvotes: 0

FDisk
FDisk

Reputation: 9436

(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png)

This will mach all images from this string:

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;

Test your regex here: https://regex101.com/r/l2Zt7S/1

Upvotes: 15

Blairg23
Blairg23

Reputation: 12075

(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png) worked really well for me.

This will match URLs in the following forms:

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

Check this regular expression against the URLs here: http://regexr.com/3g1v7

Upvotes: 4

Mark Cidade
Mark Cidade

Reputation: 100047

^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))

Upvotes: -1

shyammakwana.me
shyammakwana.me

Reputation: 5752

Addition to Dan's Answer.

If there is an IP address instead of domain.

Change regex a bit. (Temporary solution for valid IPv4 and IPv6)

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

However this can be improved, for IPv4 and IPv6 to validate subnet range(s).

Upvotes: 0

Dan
Dan

Reputation: 63460

(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?

That's a (slightly modified) version of the official URI parsing regexp from RFC 2396. It allows for #fragments and ?querystrings to appear after the filename, which may or may not be what you want. It also matches any valid domain, including localhost, which again might not be what you want, but it could be modified.

A more traditional regexp for this might look like the below.

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

EDIT See my other comment, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for karma-whoring completeness reasons.

Upvotes: 78

dkam
dkam

Reputation: 3926

Use FastImage - it'll grab the minimum required data from the URL to determine if it's an image, what type of image and what size.

Upvotes: 0

Jonny Buchanan
Jonny Buchanan

Reputation: 62813

If you really want to be sure, grabbing the first kilobyte or two of the given URL should be sufficient to determine everything you need to know about the image.

Here's an example of how you can get that information, using Python, and here's an example of it being put to use, as a Django form field which allows you to easily validate an image's existence, filesize, dimensions and format, given its URL.

Upvotes: 2

Dan
Dan

Reputation: 63460

Actually.

Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting aren't images. Try performing a HEAD request on it, and see what content-type it actually is.

Upvotes: 38

Blair Conrad
Blair Conrad

Reputation: 242100

In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details.

If you are keen on doing this, though, check out this question:

Getting parts of a URL (Regex)

Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like

(?i)\.(jpg|png|gif)$

Upvotes: 19

Related Questions