Reputation:
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
Upvotes: 4
Views: 2501
Reputation: 46187
Agreed with the "don't do it this way" answers, but, since it's tagged "regex"...
?
. *
already accepts 0 repetitions as a match, so (.*)
is exactly equivalent to (.*)?
.*
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.Upvotes: 1
Reputation: 50237
How about:
"([^/]+)/?$"
But as @Blair Conrad says - better to go with a class that encapsulates this for you....
Upvotes: 2
Reputation: 241790
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.
Upvotes: 13
Reputation:
Don't do this. Use System.IO.Path to break apart path parts and then compare them.
Upvotes: 3