Regex for parsing directory and filename

前端 未结 8 1553
南方客
南方客 2020-11-30 03:55

I\'m trying to write a regex that will parse out the directory and filename of a fully qualified path using matching groups.

so...

/         


        
8条回答
  •  误落风尘
    2020-11-30 04:22

    Most languages have path parsing functions that will give you this already. If you have the ability, I'd recommend using what comes to you for free out-of-the-box.

    Assuming / is the path delimiter...

    ^(.*/)([^/]*)$
    

    The first group will be whatever the directory/path info is, the second will be the filename. For example:

    • /foo/bar/baz.log: "/foo/bar/" is the path, "baz.log" is the file
    • foo/bar.log: "foo/" is the path, "bar.log" is the file
    • /foo/bar: "/foo/" is the path, "bar" is the file
    • /foo/bar/: "/foo/bar/" is the path and there is no file.

提交回复
热议问题