tags:

views:

932

answers:

4

I am trying to match the folder name in a relative path using C#. I am using the expression: "/(.*)?/" and reversing the matching from left to right to right to left. When I pass "images/gringo/" into the regular expression, it correctly gives me "gringo" in the first group - I'm only interested in what is between the brackets. When I pass in "images/", it fails to pick up "images". I have tried using [/^] and [/$] but neither work.

Thanks, David

+12  A: 

You're probably better off using the System.IO.DirectoryInfo class to interpret your relative path. You can then pick off folder or file names using its members:

DirectoryInfo di = new DirectoryInfo("images/gringo/");
Console.Out.WriteLine(di.Name);

This will be much safer than any regexps you could use.

Blair Conrad
+3  A: 

Don't do this. Use System.IO.Path to break apart path parts and then compare them.

Will
+2  A: 

How about:

"([^/]+)/?$"
  • 1 or more non / characters
  • Optional /
  • End of string

But as @Blair Conrad says - better to go with a class that encapsulates this for you....

toolkit
+1  A: 

Agreed with the "don't do it this way" answers, but, since it's tagged "regex"...

  • You don't need the ?. * already accepts 0 repetitions as a match, so (.*) is exactly equivalent to (.*)?
  • You rarely actually want to use .* anyhow. If you're trying to capture what's between a pair of slashes, use /([^/]*)/ or else testing against "foo/bar/baz/" will (on most regex implementations) return a single match for "bar/baz" instead of matching "bar" and "baz" separately.
Dave Sherohman