YvesR YvesR - 2 months ago 18
C# Question

C# Winforms Search Start and End string and get selection

I use a C# Winforms RichTextBox to load and show some logfiles.
Those logfiles uses ANSI escape chars to colorize the logfiles.

Found some examples to find and highlight a search string but I want to search for start and end strings, get those selections and colorize the content between.

Example:

previous text ESC[36m SOME LOG CONTENT ESC[0m Some more text


So I can load and search for the strings, but I wasn't successful to create a function that search for
ESC[36m
as first string and
ESC[0m
as second string and then return the
TextRange
of it so I can highlight it after.

UPDATE
To clarify, I do not just need the text between string-search-1 and string-search-2, I need a
TextRange
that selects the text so I can modify formatting.

Answer

Try using regular expressions. This should do it.

rtb.Text = "previous text ESC[36m SOME LOG CONTENT ESC[0m Some more text";

Regex regex = new Regex(@"ESC\[36m(.*?)ESC\[0m", RegexOptions.Multiline);
foreach (Match m in regex.Matches(rtb.Text))
{
    rtb.Select(m.Index + 7, m.Value.Length - 13);
    rtb.SelectionColor = Color.Aqua;
}
Comments