【问题标题】:Color characters based on regular expression基于正则表达式的颜色字符
【发布时间】:2012-10-12 11:39:46
【问题描述】:

我是 .Net 初学者。我想根据所选的正则表达式为富文本框中的一些字符着色。如何做到这一点?

喜欢:

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

我应该在里面写什么?使用标签也可以做到这一点吗?

【问题讨论】:

标签: c# regex windows winforms richtextbox


【解决方案1】:

如果您想遍历所有匹配项。不确定 Regex.Matches 是否曾经返回 null,因此我检查了结果。

 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;
     }
 }

【讨论】:

    【解决方案2】:

    您可以尝试将Paragraphs 与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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多