limit name size and file extention

I need regular expression for icefaces input file component, file name length should be less than 15 characters and have proper extention. I wrote this, but it fails:

^.{0,100}.+.(asf|avi|csv|pdf|doc|docx|dot|eml|gif|htm|html|idx|tif|jpg|jpeg|bmp|png|mp3|mpg|msg|ppt|pptx|pst|rtf|txt|wav|wma|xls|xlsx|zip"+ "|ASF|ASI|CSV|PDF|DOC|DOCX|DOT|EML|GIF|HTM|HTML|IDX|TIF|JPG|JPEG|BMP|PNG|MP3|MPG|MSG|PPT|PPTX|PST|RTP|TXT|WAV|WMA|XLS|XLSX|ZIP)


file name length should be less than 15

This can be achieved with a positive lookahead (?=.{0,15}$) . However, with a negative lookahead, this condition can be expressed more elegantly. We can use (?!.{16}) negative lookahead anchored at the start that means that the match should be failed if there are 16 characters.

To shorten the pattern, you may also use the embedded flag expression (?i) .

So, you may use

(?i)^(?!.{16}).+[.](?:asf|avi|csv|pdf|doc|docx|dot|eml|gif|htm|html|idx|tif|jpg|jpeg|bmp|png|mp3|mpg|msg|ppt|pptx|pst|rtf|txt|wav|wma|xls|xlsx|zip)$

See the regex demo.

Note that .+ will match any 1+ characters other than linebreak symbols, as many as possible, up to the last . followed with one of the extensions.

A bit shorterned version with ? quantifiers:

(?i)^(?!.{16}).+[.](?:asf|avi|csv|pdf|docx?|dot|eml|gif|html?|idx|tif|jpe?g|bmp|png|mp[3g]|msg|pptx?|pst|rtf|txt|wav|wma|xlsx?|zip)$

通过使用扩展功能来简化主要部分,保持简单:

^(?=.*.(?i)(asf|avi|...etc...|zip)$).{,14}$
链接地址: http://www.djcxy.com/p/45486.html

上一篇: 日志文件的MIME类型为空

下一篇: 限制名称大小和文件扩展