Regex for parsing directory and filename

2020-02-02 11:00发布

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

so...

/var/log/xyz/10032008.log

would recognize group 1 to be "/var/log/xyz" and group 2 to be "10032008.log"

Seems simple but I can't get the matching groups to work for the life of me.

NOTE: As pointed out by some of the respondents this is probably not a good use of regular expressions. Generally I'd prefer to use the file API of the language I was using. What I'm actually trying to do is a little more complicated than this but would have been much more difficult to explain, so I chose a domain that everyone would be familiar with in order to most succinctly describe the root problem.

标签: regex parsing
8条回答
Root(大扎)
2楼-- · 2020-02-02 11:57

Try this:

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

It will leave the trailing slash on the path, though.

查看更多
ら.Afraid
3楼-- · 2020-02-02 11:59

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.
查看更多
登录 后发表回答