突出显示richtextbox中的单词

时间:2015-11-03 19:17:10

标签: c#

我想知道如何在richtextbox中突出显示多个单词,例如

我搜索的单词是“la” 在文本“la langue”;

我这里有这段代码

private void Surligne(string[] mots)
    {
        foreach (string word in mots)
        {
            int Index = 0;
            while (Index < rtb.TextLength)
            {
                int wordStartIndex = rtb.Find(word, Index, RichTextBoxFinds.None);
                if (wordStartIndex != -1)
                {
                    rtb.SelectionStart = wordStartIndex;
                    rtb.SelectionLength = word.Length;
                    rtb.SelectionBackColor = Color.Yellow;
                }
                else
                    break;
                Index += wordStartIndex + word.Length;
            }
        }
    }

但它突出了la'la'ngue

我只希望它突出显示la而不是'la'langue。

如何更改代码才能执行此操作?感谢。

1 个答案:

答案 0 :(得分:0)

扩展来自@ sab669的评论,这些是在代码中建议的两种方式。确切的结果将取决于你如何确定一个单词(一个数字可以是单词的一部分吗?连接器如下划线怎么样?),但对于大多数情况,这些应该是相同的。

<强> 1。检查相邻字符

这只需要修改while循环。您必须检查相邻的字符,请记住您可能位于字符串的开头或结尾:

while (Index < rtb.TextLength)
{
    int wordStartIndex = rtb.Find(word, Index, System.Windows.Forms.RichTextBoxFinds.None);
    if (wordStartIndex == -1) 
        break;
    if ((wordStartIndex == 0 || !char.IsLetterOrDigit(rtb.Text[wordStartIndex - 1])) &&
        (wordStartIndex + word.Length >= rtb.TextLength || !char.IsLetterOrDigit(rtb.Text[wordStartIndex + word.Length])))
    {
        rtb.SelectionStart = wordStartIndex;
        rtb.SelectionLength = word.Length;
        rtb.SelectionBackColor = System.Drawing.Color.Yellow;
    }
    Index += wordStartIndex + word.Length;
}

<强> 2。使用正则表达式

这会导致代码更短,幸运的是正则表达式并不那么困难:

foreach (Match match in Regex.Matches(rtb.Text, "\\b" + word + "\\b"))
{
    rtb.SelectionStart = match.Index;
    rtb.SelectionLength = word.Length;
    rtb.SelectionBackColor = System.Drawing.Color.Yellow;
}

我使用了\b,它表示单词字符和非单词字符之间的边界。有关详细信息,您可以查看MSDN page,其中还会提供有关这些字符究竟是什么的信息。

相关问题