Regex formula for a file name

2019-09-24 09:48发布

问题:

I would like to allow a field in a form I have to allow only file names to be accepted. File names looks like this:

431714620407606949.jpg

18 digits [dot] jpg/gif/ico/png/tiff

Also I would like the field to accept multiple file name entries, so I want it to be like this:

431714620407606949.jpg,431714620407674859.jpg,837593620407606949.jpg

回答1:

This should do it: http://regexr.com?353i8 (/([\d]{18}\.)(jpg|png|gif)/g)

This site will help you with your regex'



回答2:

The following will match exactly one of those filenames:

/^\d{18}\.(jpg|gif|ico|png|tiff)$/

That is:

^                         beginning of string
\d{18}                    18 digits
\.                        a literal .
(jpg|gif|ico|png|tiff)    one of those extensions
$                         end of string

To match more with commas in between:

/^\d{18}\.(jpg|gif|ico|png|tiff)(,\d{18}\.(jpg|gif|ico|png|tiff))*$/

That is, the same pattern I already explained in detail, followed by zero or more occurrences of a comma plus the same pattern.

If you want to match upper- or lowercase file extensions add the i flag to the end:

/^\d{18}\.(jpg|gif|ico|png|tiff)(,\d{18}\.(jpg|gif|ico|png|tiff))*$/i