tags:

views:

74

answers:

4

I'm trying to locate the number of matches in a relative path for directory up references ("..\"). So I have the following pattern : "(\.\.\\)", which works as expected for the path "..\..\a\b" where it will give me 2 successful groups ("..\"), but when I try the path "..\a\b" it will also return 2 when it should return 1. I tried this in a reg ex tool such as Expresso and it seems to work as expected in there but not in .net, any ideas?

+1  A: 

Try this instead:

(\.\.\\)

The dots (.) were matching any character, not the literal value. To match the literal value you must escape them with a leading backslash.

Andrew Hare
That's what I have currently, but slashes got removed when I submitted the question. I have edited the post to now include them.
Rubans
A: 

I'm getting the correct answer, try the following:

Console.WriteLine(Regex.Matches(@"..\..\a\b", @"(\.\.\\)").Count); //2
Console.WriteLine(Regex.Matches(@"..\a\b", @"(\.\.\\)").Count); //1

Did you escape or use literal strings for the \ in .NET?

Yuriy Faktorovich
Thanks so obviously my usage of it must be wrong in code since yours confirms Expresso's results. Will investigate.
Rubans
Thanks. Looks like the issue was related to me using Match instead Matches which returns a collection.
Rubans
A: 

Since Expresso runs on .net, your statement "I tried this in a reg ex tool such as Expresso and it seems to work as expected in there but not in .net" doesn't seem to make a lot of sense.
What this suggests me is that it's not the regular expression which is the problem, but your usage of it.
Have a close look at the Regex method you're using to collect results and how you process those results, that might be where the problem lies.

Hope this helps!

Task
I think the posts above under stood the question ok ,will following their suggestions and report back.
Rubans
Hey, look at that, I was right! You were using Match instead of Matches, so it was a usage problem. Good to know you got it fixed.
Task
A: 

Did you escape the backslahes to escape the dots in your Regex? I.e. "\\.\\.\\\\" or @"\.\.\\"?

You could always not use Regex for this task and use

Int32 count = url.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries)
                 .Where(s => s == "..")
                 .Count();

instead. =)

Jens