Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for extracting filename from path

Tags:

regex

I need to extract just the filename (no file extension) from the following path....

\\my-local-server\path\to\this_file may_contain-any&character.pdf

I've tried several things, most based off of something like http://regexr.com?302m5 but can't quite get there

like image 951
Webnet Avatar asked Feb 20 '12 14:02

Webnet


3 Answers

^\\(.+\\)*(.+)\.(.+)$

This regex has been tested on these two examples:

\var\www\www.example.com\index.php
\index.php

First block "(.+\)*" matches directory path.
Second block "(.+)" matches file name without extension.
Third block "(.+)$" matches extension.

like image 123
Marko Medojević Avatar answered Nov 14 '22 20:11

Marko Medojević


This will get the filename but will also get the dot. You might want to truncate the last digit from it in your code.

[\w-]+\.

Update

@Geoman if you have spaces in file name then use the modified pattern below

[ \w-]+\.      (space added in brackets)

Demo

like image 20
Hammad Khan Avatar answered Nov 14 '22 21:11

Hammad Khan


This is just a slight variation on @hmd's so you don't have to truncate the .

[ \w-]+?(?=\.)

Demo

Really, thanks goes to @hmd. I've only slightly improved on it.

like image 15
campeterson Avatar answered Nov 14 '22 19:11

campeterson