开发者

What would a regex for common file name extensions for images look like?

I am starting on making so images turns out as small thumbnails.

But I need a regular expression to check if it contains *.jpg, *.jpeg, .*png, *.gif

开发者_C百科

How can that be made?


\.(?:jpe?g|png|gif)\b

will match if the tested string contains .jpeg, .png or one of the other alternatives.

\.(?:jpe?g|png|gif)$

will match if the tested string ends in .jpeg, .png etc.


To match the entire filename of images

(^|\s+).+\.(jpe?g|png|gif|tiff)(\s+|$)

*NOTE: the ^ and $ match the beginning and end of the string, so if you are pulling the names out of some larger text, remove those characters. By adding the option of string terminator (^ or $) of space, it makes the filename have to appear at the beginning/end of the string or to be flanked by spaces. Since spaces are allow in filenames, this may/may not work for the OP, however, we don't have much information on the context in which he plans to use the expression.


To prevent a filename that is just a dot:

^.?[^\.]+\.(jpe?g|png|gif|tiff)$


You don't need to have a regular expression for that...

But if you really want a regex, you can use

(jpeg|png|gif|jpg)$

It should make it.

I recommand you to use substr, it will run faster.

EDIT
Add a period to check for extension, not just end of name (or longer extension), e.g. myjpg or otherfile.xgif:

\.(png|gif|jpe?g)$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜