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

 

2 comments on “Regex – Extract filename from path

  1. Marcel Snoeck

    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.

    C:\xampp\htdocs\team360_new\media\com_acymailing\upload\userfiles\5783663a50f9d-Avatar_Marcel_200x200.jpg

    /var/www/vh64157/1/team360.nl/media/com_acymailing/upload/userfiles/5783663a50f9d-Avatar_Marcel_200x200.jpg

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

    Thanks for you reply

  2. fstarred

    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.

    [\w-]+(?:\.\w+)*$

    or

    [\w-_]+(?:\.\w+)*$

    Best regards
    Starred Mediasoft

Leave a Reply

Your email address will not be published. Required fields are marked *