Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex extension and language

I looking into validating some file names. But cant figure out correct regex file names can be anything, but need to check if filename ends with

  1. _ underscore
  2. en or ru or cy (country code 2 letters)
  3. . (dot)
  4. extensions (jpeg, jpg, mp4, png, gif)

so file

my_file_dummy_name.jpeg - not valid
my_file_dummy_name_en.jpeg - valid

For Now I tried this (and is working but maybe there is better solution)

/(\_\w.\.\w+)/g

One more:

/(\_[a-z]{2}\.[a-z]{3,4})/g
like image 297
Froxz Avatar asked Jul 28 '16 11:07

Froxz


Video Answer


2 Answers

The problem with your original regex is that, while it would match the filenames you want to allow, it would also match things you don't want.

For example, the following regex

/(\_\w{2}\.\w+)/g

would match the file my_file_dummy_name_de.mpeg, which is a video file from Germany. Clearly, we wouldn't want to watch this in the first place.

Try this regex:

_(en|ru|cy)\.(jpeg|jpg|mp4|png|gif)$

Demo here:

Regex101

like image 189
Tim Biegeleisen Avatar answered Oct 20 '22 16:10

Tim Biegeleisen


If you want the regex to do all the checking for you, there's a more strict way to go about this:

/_(en|ru|cy)\.(jpeg|jpg|mp4|png|gif)$/

This way you ensure all those constraints you mentioned. Also, there's no need for the global flag, as we're only interested in the end of the string (this is why I put the EOL anchor $). You could add, though, the ignore case flag if there's a possibility of mixed case in the filenames.

like image 37
rgoliveira Avatar answered Oct 20 '22 16:10

rgoliveira