I am currently working on a exception reporting system for work. As part of the system I am Creating a way to automatically create a bug in our bug reporting system when someone creates an error report or increase the count when an error has occured more than once. To do this I created an regular expression that grabs the relative filename and line number, I used this code:

Regex regex = new Regex("^.*\\(?'filename'.*):line (?'line'[0-9].)");
Match match = regex.Match(stackTrace);

I tested the code and got an following error

parsing "^.*\(?'filename'.*):line (?'line'[0-9].)" - Too many )'s.

After googleing i found exactly nothing that would help and 2 hours after that I came up with a nasty hack, my thinking was the proble is to do with the "\\" so how about replacing all the "\" with an "`" and then using String.Replace to replace the string(see below) it worked.

Regex regex = new Regex("^.*@(?'filename'.*):line (?'line'[0-9].)");
Match match = regex.Match(stackTrace.Replace('\\', '@'));

Probably someting you want to fix Microsoft.

1 comments:

Anonymous said...

Your first expression has a bug. The '\' must be escaped twice - once for C# and again for regex - otherwise it literalizes your grouping-left paren. Try something like this:

Regex("^.*\\\\(?'filename'.*):line (?'line'[0-9].)")

or, to remove the need to escape '\' for C#:

Regex(@"^.*\\(?'filename'.*):line (?'line'[0-9].)")