Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

image - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*.(?: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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...