Some time ago, I had to make a project that required syntax highlighting - luckily I wasn't the one who had to make that part. However the version used in the project was more complicated - so I decided to make a tutorial that will teach you how to make a basic syntax highlighter (with Regex).

I'll be using the RichTextBox control - using the simple TextBox might seem to be better but it's kinda difficult to implement the word coloring function without getting into other troubles.

Anyhow it needs to be improved - I tried to keep things as simple as possible. This program is just to show you the basic idea behind a syntax highlighter.

Preview

1.How It Works:

This part is meant to explain the main idea behind the whole process. The algorithm will follow these steps each time the text in the RichTextBox changes:

1) scan the content using different Regex patterns

2) store the original caret's position, so we can go back from where we started, after the highlighting is done

3) focus another control - this is a trick that I know from a friend, you have to do this to avoid the blinking effect

4) highlight! - simply changing the SelectionColor...

5) move the caret back & reset the color

6) restore focus to the RichTextBox

Each Regex Match contains it's positon and it's length - we'll need these for highlighting. All the matches are stored in a MatchCollection list. At the end, there'll be multiple lists, as an example: there'll be a list that contains strings, another list that contains comments, etc.

2.Coding Part

The most complicated part is the Regex part - everything else should be pretty straightforward. And since the code is not that complicated, I'll post the complete source: