Regular expression to remove a file's extension

后端 未结 9 2033
死守一世寂寞
死守一世寂寞 2020-11-30 01:09

I am in need of a regular expression that can remove the extension of a filename, returning only the name of the file.

Here are some examples of inputs and outputs:<

9条回答
  •  北海茫月
    2020-11-30 01:47

    /^(.+)(\.[^ .]+)?$/
    

    Above pattern is wrong - it will always include the extension too. It's because of how the javascript regex engine works. The (\.[^ .]+) token is optional so the engine will successfully match the entire string with (.+) http://cl.ly/image/3G1I3h3M2Q0M


    Here's my tested regexp solution.

    The pattern will match filenameNoExt with/without extension in the path, respecting both slash and backslash separators

    var path = "c:\some.path/subfolder/file.ext"
    var m = path.match(/([^:\\/]*?)(?:\.([^ :\\/.]*))?$/)
    var fileName = (m === null)? "" : m[0]
    var fileExt  = (m === null)? "" : m[1]
    

    dissection of the above pattern:

    ([^:\\/]*?)  // match any character, except slashes and colon, 0-or-more times,
                 // make the token non-greedy so that the regex engine
                 // will try to match the next token (the file extension)
                 // capture the file name token to subpattern \1
    
    (?:\.        // match the '.' but don't capture it
    ([^ :\\/.]*) // match file extension
                 // ensure that the last element of the path is matched by prohibiting slashes
                 // capture the file extension token to subpattern \2
    )?$          // the whole file extension is optional
    

    http://cl.ly/image/3t3N413g3K09

    http://www.gethifi.com/tools/regex

    This will cover all cases that was mentioned by @RogerPate but including full paths too

提交回复
热议问题