使用带标签的RichTextBox查找函数

时间:2013-04-20 10:22:37

标签: richtextbox

我要做的是将其设置为用户可以在文本框中键入,然后单击按钮,它将在richtextbox中搜索他们正在查找的内容,如果找到了某些内容,则会更改标签。    (实例)     `     Button = btn_Search

Textbox = InputBox

RichTextBox = rtb

Label = Results`

2 个答案:

答案 0 :(得分:0)

使用此方法查找RichTextBox内的任何文字。

public int FindMyText(string searchText, int searchStart, int searchEnd)
{
    // Initialize the return value to false by default.
    int returnValue = -1;

    // Ensure that a search string and a valid starting point are specified.
    if (searchText.Length > 0 && searchStart >= 0) 
    {
        // Ensure that a valid ending value is provided.
        if (searchEnd > searchStart || searchEnd == -1)
        {    
            // Obtain the location of the search string in richTextBox1.
            int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
            // Determine whether the text was found in richTextBox1.
            if(indexToText >= 0)
            {
                // Return the index to the specified search text.
                returnValue = indexToText;
            }
        }
    }

    return returnValue;
}

像这样调用这个方法:

var res= FindMyText("hello",0. richTextBox1.Text.Length);

现在如果res>-1,这意味着肯定匹配,那么你可以设置你的标签,即

if(res>-1){
        lbl1.Text = "hello found";
}

来源herehere

答案 1 :(得分:0)

另一种搜索更干净的文本的方法如下,但首先需要添加 项目的 System.Text.RegularExpressions 命名空间;

private void SearchButton_Click(object sender, EventArgs e)
    {
        if (textBox1.TextLength >= 1)
        {
            string word = textBox1.Text;//The text you want to search.
            Regex searchterm = new Regex(word);//A Regular Expression is most efficient way of working with text.
            MatchCollection matches = searchterm.Matches(richTextBox1.Text);
            if (matches.Count >= 1)
            { 
                Results=matches.Count.ToString();//Your label to display match instances.
                richTextBox1.SelectAll();
                richTextBox1.SelectionBackColor = Color.White;
                richTextBox1.DeselectAll();
                foreach (Match match in matches)
                {
                    richTextBox1.Select(match.Index, match.Length);
                    richTextBox1.SelectionBackColor = Color.Orange;
                    richTextBox1.DeselectAll();
                }
            }
        }
    }

这应该可以完成这项工作,此外,如果您想指定其他搜索选项,请将Regex searchterm的行替换为下面的任何人,

不区分大小写

  

Regex searchterm = new Regex(word,RegexOptions.IgnoreCase);

全字搜索

  

Regex searchterm = new Regex(@“\ b”+ word +“\ b”);

案例不敏感和全字搜索

  

Regex searchterm = new Regex(@“\ b”+ word +“\ b”,RegexOptions.IgnoreCase);

还有一件事,正则表达式搜索默认情况下区分大小写。