正则表达式检查有效的URL是否以.jpg,.png或.gif结尾 [英] Regex to check if valid URL that ends in .jpg, .png, or .gif

查看:1175
本文介绍了正则表达式检查有效的URL是否以.jpg,.png或.gif结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户提交有效但也是图片的网址,以.jpg,.png或.gif结尾。

解决方案

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

这是来自 RFC 2396 。它允许在文件名后面显示 #fragments ?querystrings ,这可能是您想要的,也可能不是。它还匹配任何有效域,包括 localhost ,这可能不是你想要的,但可以修改。



更传统的正则表达式可能如下所示。

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

编辑请参阅我的其他评论,虽然没有完全回答这个问题,但我认为在这种情况下它可能更有用。但是,我将这里留给 karma-whoring 完整性原因。


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

解决方案

(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?: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.

这篇关于正则表达式检查有效的URL是否以.jpg,.png或.gif结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆