Martin
Martin

Reputation: 777

regular expression for file name - 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)

Upvotes: 2

Views: 2022

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

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)$

Upvotes: 2

Bohemian
Bohemian

Reputation: 425083

Keep it simple by using a look ahead for the extension to keep the main part simple:

^(?=.*\.(?i)(asf|avi|...etc...|zip)$).{,14}$

Upvotes: 0

Related Questions