Regex – Extract filename from path

Use Regex to extract path or filename

To extract path without filename, or extract only filename, there are many regex possible.

Surfing through the net I have found some interesting solution:

Extract path without filename

Extract only filename

Notice that this will work even on filename without any extension

Extract extension of filename



  1. I am Trying to extract full filename from the complete path + filename.

    But The problem of the above regex “\w+(?:\.\w+)*$” it doesn’t execpt _ (underscore) in filename

    And I cannot use this in dos format string.



    These are the to sample string I would like to extract full filename

    Thanks for you reply

  2. From your sample string, the issue is due to ‘-‘ char that is not included in the regex.
    About the underscore character, the \w+ can include it depending on the system you run regex.

    Try the following with your two examples above.




    Best regards
    Starred Mediasoft

  3. How do I extract only filename which includes more than one dot or no dot at all from unix path such as /home/user/.my.hidden.file, /home/user/my.file.ext /home/user/myfile respectively .my.hidden.file, my.file (without its extension), myfile?

Leave a Reply

Your email address will not be published.

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see