How to select text from the RichTextBox and then color it?

Here’s some code you can build on in order to achieve the functionality you want.

private void ColourRrbText(RichTextBox rtb)
{
    Regex regExp = new Regex("\b(For|Next|If|Then)\b");

    foreach (Match match in regExp.Matches(rtb.Text))
    {
        rtb.Select(match.Index, match.Length);
        rtb.SelectionColor = Color.Blue;
    }
}

The CodeProject article Enabling syntax highlighting in a RichTextBox shows how to use RegEx in a RichTextBox to perform syntax highlighting. Specifically, look at the SyntaxRichtTextBox.cs for the implementation.

Leave a Comment