Regex for extracting filename from path

前端 未结 17 544
时光取名叫无心
时光取名叫无心 2020-12-03 01:02

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<

相关标签:
17条回答
  • 2020-12-03 01:25

    If anyone is looking for a windows absolute path (and relative path) javascript regular expression in javascript for files:

    var path = "c:\\my-long\\path_directory\\file.html";
    
    
    ((/(\w?\:?\\?[\w\-_\\]*\\+)([\w-_]+)(\.[\w-_]+)/gi).exec(path);
    

    Output is:

    [
    "c:\my-long\path_directory\file.html", 
    "c:\my-long\path_directory\", 
    "file", 
    ".html"
    ]
    
    0 讨论(0)
  • 2020-12-03 01:25

    I use @"[^\\]+$" That gives the filename including the extension.

    0 讨论(0)
  • 2020-12-03 01:26

    Does this work...

    .*\/(.+)$
    

    Posting here so I can get feedback

    0 讨论(0)
  • 2020-12-03 01:27

    I'm using this regex to replace the filename of the file with index. It matches a contiguous string of characters that doesn't contain a slash and is followed by a . and a string of word characters at the end of the string. It will retrieve the filename including spaces and dots but will ignore the full file extension.

    const regex = /[^\\/]+?(?=\.\w+$)/
    
    console.log('/path/to/file.png'.match(regex))
    console.log('/path/to/video.webm'.match(regex))
    console.log('/path/to/weird.file.gif'.match(regex))
    console.log('/path with/spaces/and file.with.spaces'.match(regex))

    0 讨论(0)
  • 2020-12-03 01:34

    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

    0 讨论(0)
  • 2020-12-03 01:35

    Here's a slight modification to Angelo's excellent answer that allows for spaces in the path, filename and extension as well as missing parts:

    function parsePath (path) {
        var parts = (/(\w?\:?\\?[\w\-_ \\]*\\+)?([\w-_ ]+)?(\.[\w-_ ]+)?/gi).exec(path);
        return {
            path: parts[0] || "",
            folder: parts[1] || "",
            name: parts[2] || "",
            extension: parts[3] || "",
        };
    }
    
    0 讨论(0)
提交回复
热议问题