I am looking to create a list of file inside a folder, all matching a regex. But the regex crash whenever I put a path containing backslash inside the regex.
string test = @"C:\TEMP"; // or "C:\\TEMP"
Regex reg = new Regex(test + "\\" + "tstNL02" + @"_(.*).csv"); // it crash here
FileList = Directory.GetFiles(test).Where(path => reg.IsMatch(path)).ToList();
ArgumentException: parsing "C:\TEMP\tstNL02_(.*).csv" - Unrecognized escape sequence \T.
As far as I know, using a @ or escaping the backslash should prevent the regex from interpreting backslashes in a string as an escaping character (and if I remove test from the regex but leave the \\, regex doesn't crash).
If I put @"C:\\TEMP" the Regex doesn't parse any and the match fail C:\\TEMP\tstNL02_(.*).csv
I fixed my problem by going another way but I was wondering why and how to fix this backslash-in-a-variable thing ?
Edit: problem didn't came from regex but from the fact I was using the same string for regex and Directory.GetFiles. Adding escaping backslashes to the string so Regex worked correctly would cause Directory.GetFiles to not escape those added backslashes, thus not matching files