问题描述
我希望用户提交一个有效但也是图像的 URL,以 .jpg、.png 或 .gif 结尾.
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))(?:?([^#]*))?(?:#(.*))?
这是来自 RFC 2396 的官方 URI 解析正则表达式的(稍微修改)版本.它允许 #fragments
和 ?querystrings
出现在文件名之后,这可能是也可能不是你想要的.它还匹配任何有效的域,包括 localhost
,这也可能不是您想要的,但可以修改.
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 completeness reasons.
这篇关于正则表达式检查是否以 .jpg、.png 或 .gif 结尾的有效 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!