简体   繁体   中英

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

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? Ie "\\\\.\\\\.\\\\\\\\" 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. =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM