March 1, 2011

Filtering a Multiline string Line by Line using a Regular Expression

For other regular expression stuff see also this blog
This routine filters a string containing multiple lines using the supplied regular expression filter. Set the invert parameter to true if you want the results inverted
private string Filter(string reportText, string regExFilter, bool invert)
{
    if (regExFilter.Length > 0)
    {
        StringBuilder output = new StringBuilder();
        string[] lines = reportText.Split(
          new string[] { Environment.NewLine }, 
          StringSplitOptions.None);
        foreach (string line in lines)
        {
            if ((line.Length > 0))
            {
                bool matches = Regex.IsMatch(line, regExFilter,
                                             RegexOptions.None);
                if ((matches && !invert) || (!matches && invert))
                    output.AppendLine(line);
            }
        }
        return output.ToString();
    }
    else
    {
        return reportText;
    }
}

No comments: