David
David

Reputation:

Regular Expressions and Relative File Paths

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

Answers (4)

Dave Sherohman
Dave Sherohman

Reputation: 46187

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.

Upvotes: 1

toolkit
toolkit

Reputation: 50237

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....

Upvotes: 2

Blair Conrad
Blair Conrad

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

user1228
user1228

Reputation:

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

Upvotes: 3

Related Questions