如何在RichTextBox中找到重复的文本?

时间:2009-08-07 12:23:46

标签: c#

如何在RichTextBox中找到重复的文本?我也需要改变颜色。

3 个答案:

答案 0 :(得分:4)

要查找重复的单词,您可以按空格分割文本,按字母顺序排序,并通过单词数组执行单个循环来查找重复的实例。

重复的短语更难以检测,因为您需要尝试单词的组合,这是事物变得高度递归的地方。

答案 1 :(得分:1)

匹配字符串中重复的单词: (来自http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }
    }    
}

要更改RichTextBox中文本片段的颜色:

RichTextBox rtb = new RichTextBox();
rtb.SelectionStart = 4;
rtb.SelectionLength = 7;
rtb.SelectionColor = Color.Red;

答案 2 :(得分:0)

试试这个:

string value = "She sells sea shells by the sea shore";
Regex.Split(value, @"\W+").ToList()
    .GroupBy(w => w)
    .Where(w => w.Count() > 1)
    .Select(w => w.Key).ToList()
    .ForEach(w => Console.WriteLine("'{0}' repeats in the string", w));