title: c# - Is there A Faster Way to Highlighting Regex Matches (RichTextBox)
body: <p>I use RichTextBox for testing REGEX expression, with the code like:</p>
  
  <pre><code>rtbMain.SelectAll();
  rtbMain.SelectionColor = Color.Black;
  rtbMain.SelectionBackColor = Color.White;
  Regex regex = new Regex(txtRegexPattern.Text, regexOptions);
  Match matches = regex.Match(txtTest.Text);
  while (matches.Success)
  {
      rtbMain.Select(matches.Index, match.Length);
      rtbMain.SelectionColor = Color.Red;
      rtbMain.SelectionBackColor = Color.Black;
  }
  </code></pre>
  
  <p>But this method becomes too slow as soon as there are more than a few thousand (1000+) characters to be highlighted. I know I could delay processing, so that code gives user a chance to enter the whole Regular Expression, but still I think RichTextBox highlighting is working too slow.</p>
  
  <p>I've searched the Google for different approaches and ways to speed up current solution, but I didn't have luck. I noticed that there are a few text editors which allow "syntax highlighting" (like ScintillNET, Avalon,...) but they use XML as input, so I think using them for my project (generating XML on every KeyUp event) wouldn't be the "best practice".</p>
  
  <p>I have found and tested a "Fast colored Textbox" here: <a href="https://github.com/PavelTorgashov/FastColoredTextBox" rel="nofollow">https://github.com/PavelTorgashov/FastColoredTextBox</a> ...but the problem with this one is that it replaces the paste content while it uses its own new-line and tab character, and I cant use it in REGEX tester.</p>
  
  <p>Is there any faster way to highlight all matches, maybe using a different user control?</p>
  
  <p>EDIT:</p>
  
  <p>APPROACH 1: Would generating the underlying RTF document be faster? I tried but had some problems with special characters, so I could test highlighting of the whole document, but it seemed to work quite fast with normal characters in a single line. I paused working on this since I read constructing RTF's can be quite hard, and I think I couldn't use none of the existing RTF libraries.</p>
  
  <p>APPROACH 2: I am able to get only the displayed portion of RichTextBox, so I was thinking to only highlight that part. I guess this would significantly reduce processing (depends on RTB size), but I would need to trigger highlighting every time user scrolls; I'm not sure this would work well and create a decent user experience, so haven't tried it out yet.</p>
  
  <p>Would anyone recommend any of the approaches above or maybe any others?</p>