Regular expression to remove a file's extension

后端 未结 9 2028
死守一世寂寞
死守一世寂寞 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:36

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

    Test cases where this works and others fail:

    • ".htaccess" (leading period)
    • "file" (no file extension)
    • "send to mrs." (no extension, but ends in abbr.)
    • "version 1.2 of project" (no extension, yet still contains a period)

    The common thread above is, of course, "malformed" file extensions. But you always have to think about those corner cases. :P

    Test cases where this fails:

    • "version 1.2" (no file extension, but "appears" to have one)
    • "name.tar.gz" (if you view this as a "compound extension" and wanted it split into "name" and ".tar.gz")

    How to handle these is problematic and best decided on a project-specific basis.

提交回复
热议问题