Tuesday, June 9, 2015

Parsing msbuild output through RegEx

I wanted to be able to parse the output from msbuild to extract errors and warnings from both Microsoft and third party tools.

I found several posts describing the format of messages compliant with msbuilds parsing of errors and warnings but I could not find a regular expression that would do the same thing.

msbuild visual studio aware error messages and message formats

So I worked one out that I think works in most cases

const RegexOptions OPTIONS = RegexOptions.Compiled |
RegexOptions.IgnoreCase |
RegexOptions.IgnorePatternWhitespace |
RegexOptions.ExplicitCapture |
RegexOptions.Singleline;

// in multi-line $ == LF but not CR so use [^\r\n]+
const string PATTERN = @"
# token to match microsoft standard error format for tools
(^(
((?
(?:(?:[a-z]:|\\\\[a-z0-9_.$-]+\\[a-z0-9_.$-]+)\\| # Drive or UNC
\\?[^\\/:*?<>|\r\n]+\\?)                          # Relative path
(?:[^\\/:*?<>|\r\n]+\\)*                          # Folder
[^\\/:*?<>|\r\n]*                                    # File name
(\((?\d)(,(?\d))?\)?:)?         # (line#[,col#]) - optional
|(?\w)):\s?)?                                # or toolname
(\w+\s)?                                                 # optional severity
(?error|warning)                        # error or warning
(\s\w+\d)?                                              # error code - optional
:\s*                                                         # white space
(?.*$))                                  # error message
)
";

It looks really scary but it is reasonably simple if you take it a chunk at a time.

Named captures:
- the file the error happened in (optional)
- the line information (optional)
- the column (optional)
- the tool throwing the error (optional)
- the error level 
- the error message