-1

I am a .Net beginner. I want to color some characters inside a rich text box based on the selected regular expression. How to do this?

Like:

if (Regex.IsMatch(richTextBox, @"^[a-m]{1}$"))
{
   ??? //coloring that particular character of richTextBox
}

What should I write in it? can the same done using label?

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • possible duplicate of: http://stackoverflow.com/questions/2527700/change-color-of-text-within-a-winforms-richtextbox – hometoast Oct 12 '12 at 11:42
  • check this: http://stackoverflow.com/questions/12437880/richtextbox-coloring-behaviour – Kapil Khandelwal Oct 12 '12 at 11:50
  • @KPL can this be done using labels. because i used label in my project not richtextbox( my friend suggested to use richtextbox instead). – Mr_Green Oct 12 '12 at 12:05

2 Answers2

2

If you want to iterate through all matches. Not sure whether Regex.Matches ever returns null, thus I checked the result.

 MatchCollection matches = Regex.Matches(rtb.Text, @"^[a-m]{1}$");
 if (matches != null && matches.Count > 0)
 {
     foreach (Match m in matches)
     {
         rtb.Select(m.Index, m.Length);
         rtb.SelectionColor = Color.Blue;
     }
 }
mbue
  • 1,591
  • 2
  • 14
  • 34
0

You could try using Paragraphs with Runs

Paragraph para = new Paragraph {
    Foreground = Brushes.Red,
};
para.Inlines.Add(new Bold(new Run(matchingString)));
para.Inlines.Add(new Run(regularText));
myRichTextBox.Document.Blocks.Add(para);

etc

Pyritie
  • 543
  • 4
  • 16