Issue with my regular expression?
I'm trying to locate the number of matches in a relative path for directory up references ("..\
"). So I have the following pattern : "(\.\.\\)
", which wor开发者_JS百科ks 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?
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.
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?
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!
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. =)
精彩评论