Search code examples
regexfilenames

regex match file with multiple extension


I have several strings like this

XYZ_TEST_2017.txt

ASD_TEST_2017.txt.tmp

I need to extract only those strings ending with .txt

So I'm using this regex:

[A-Z]{3}_TEST_[0-9]{4}.txt

However I still get the strings with multiple extensions like the second one (.txt.tmp)

See my regex demo.

How can I handle it?


Solution

  • To have your regex match everything up to the end, append an "end-of-text marker" ($) to your pattern like this:

    [A-Z]{3}_TEST_[0-9]{4}\.txt$
    

    As you may have noticed, I also escaped the dot, otherwise this filename would match as well:

    SOM_TEST_1234Etxt
    

    The dot (.) would match any character (depending on your flags, even newline and carriage return), in this case, the E before txt.