Extension and regular expression language

I am studying some file names. But I can not determine the correct regular expression, the file names can be any, but I need to check whether the file name ends with

  • _ underscore
  • en or ru or cy (country code 2 letters)
  • . (Dot)
  • extensions (jpeg, jpg, mp4, png, gif)

therefore file

my_file_dummy_name.jpeg - not valid my_file_dummy_name_en.jpeg - valid 

I have tried this currently (and it works, but maybe there is a better solution)

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

Another:

 /(\_[az]{2}\.[az]{3,4})/g 
+6
source share
2 answers

The problem with your original regex is that although it will match the names of the files you want to resolve, it will also match those things that you don't need.

For example, the following regular expression

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

will correspond to the file my_file_dummy_name_de.mpeg , which is a video file from Germany. It is clear that we would not want to watch this in the first place.

Try this regex:

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

Demo here:

Regex101

+10
source

If you want the regex to do all the checks for you, a more rigorous way to do this:

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

In this way, you provide all the restrictions that you talked about. In addition, there is no need for the g lobal flag, since we are only interested in the end of the line (which is why I anchored EOL $ ). However, you can add the i gnore flag flag if there is the possibility of a mixed case in file names.

+2
source

All Articles