-4

CLARIFICATION: I am not asking for a pattern. I am asking why a pattern works in PHP and JavaScript but not in .Net.

I am trying to get the bottom level folder from a path. The pattern works in PHP and JavaScript but returns an unexpected result in .Net. I would like to understand why .Net returns what it returns with this pattern.

Given this path:

"c:\level0\level1\level2\filename.ext"

I am trying to match

"level2"

This is the pattern I am using: (editor keeps taking out the slashes, so here is a picture:

Regex pattern

What I expect to match :

level2

What C# matches:

c:\level0\level1

For completeness, here is the pattern in the RegEx instance: VS pattern

How does this pattern need to be specified for .Net to match the bottom level folder?

Metaphor
  • 6,157
  • 10
  • 54
  • 77
  • Something like `Regex.Match(path, @".*\\([^\\]+)\\.*").Groups[1].Value`. Or with named group `Regex.Match(path, @".*\\(?[^\\]+)\\.*").Groups["name"].Value` – Kalten Sep 21 '18 at 19:45
  • 1
    Instead of editing the post and attacking the user in the edit message, you _could_ leave a comment and ping them to ask for clarification. – jhpratt Sep 22 '18 at 01:47

2 Answers2

6

If you have the right security permissions on the filesystem you run the code on you don't need to use Regex for this, the framework already contains what you need by way of FileInfo:

new FileInfo(@"c:\level0\level1\level2\filename.ext").Directory.Name

If you dont have access to the file system you can also use Path.GetDirectoryName() which is a bit more straightforward than Regex I think:

string directoryPath = Path.GetDirectoryName(@"c:\level0\level1\level2\filename.ext");

//outputs "c:\level0\level1\level2"

string folder = directoryPath.Split(Path.DirectorySeparatorChar).Last();

Fiddle for the latter of the two answers here

maccettura
  • 10,514
  • 3
  • 28
  • 35
  • Thank you for this suggestion, I will .use it. The question, however, is about RegEx and I would like to understand why this pattern doesn't work in .Net. – Metaphor Sep 22 '18 at 05:10
1

You could also just use Split and linq:

string path = @"c:\level0\level1\level2\filename.ext";
string result = path.Split('\\').Reverse().Skip(1).First();
//outputs: level2
Magnetron
  • 7,495
  • 1
  • 25
  • 41