Regular Expressions and Relative File Paths

c#, regex

Solution

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.

Problem

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

Original source