Regex for extracting filename from path

前端 未结 17 656
时光取名叫无心
时光取名叫无心 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:48

    TEST ^(.*[\\\/])?(.*?)(\.[^.]*?|)$

    example:

    /^(.*[\\\/])?(.*?)(\.[^.]*?|)$/.exec("C:\\folder1\\folder2\\foo.ext1.ext")
    

    result:

    0: "C:\folder1\folder2\foo.ext1.ext"
    1: "C:\folder1\folder2\"
    2: "foo.ext1"
    3: ".ext"
    

    the $1 capture group is the folder
    the $2 capture group is the name without extension
    the $3 capture group is the extension (only the last)

    works for:

    • C:\folder1\folder2\foo.ext
    • C:\folder1\folder2\foo.ext1.ext
    • C:\folder1\folder2\name-without extension
    • only name
    • name.ext
    • C:\folder1\folder2\foo.ext
    • /folder1/folder2/foo.ext
    • C:\folder1\folder2\foo
    • C:\folder1\folder2\
    • C:\special&chars\folder2\f [oo].ext1.e-x-t

提交回复
热议问题