Thursday, January 05, 2017

Extension method to dump Highlighted search results in Linqpad

Here's an extension method which lets you output the found results as html.

For example, if you wanted to show the result of a search and replace, given:
 var text = "An apple a day keeps the doctor away\n you can say that any day of the year today or tomorrow.";
 var find = "day";
 var replace = "week";
 
 text.HighlightText(find).Dump("Original text");
 text.Replace(find, replace).HighlightText(replace).Dump("updated text");

The result would be:
Original text
An apple a 
day
 keeps the doctor away
 you can say that any 
day
 of the year.
updated text
An apple a 
week
 keeps the doctor away
 you can say that any 
week
 of the year.

See extension method below:


public static class MyExtensions
{
 public static DumpContainer HighlightText(this string text, string find){
  var dc = new DumpContainer();
  var sb = new StringBuilder();
  foreach(var line in text.Split('\n'))
  {
   if(line.Contains(find))
   {
    var before_ix = line.IndexOf(find);
    var beforeText = line.Substring(0, before_ix);
    var afterText = line.Substring(before_ix + find.Length);
    dc.Content =  Util.HorizontalRun(false, dc.Content, beforeText, Util.Highlight(find), afterText, "\n");
   }
   else 
   {
    sb.AppendLine(line);
    dc.Content = Util.HorizontalRun(false,dc.Content,  line, "\n");
   }
  }
  return dc;
 }
}

Known limitations:

  1. The result this finds one match per line.
  2. carriage returns are stripped from the result - a limitation of the HorizontalRun util class

1 comment:

TheXenocide said...

I was looking for something slightly more robust and wound up having to write my own so I just thought I'd share the results in case anyone else coming across this finds it useful :)

https://gist.github.com/TheXenocide/23bf89b18e29b4ca35f95207e352f331