我想要做的是让用户可以在文本框中输入然后单击一个按钮,它会在 Richtextbox 中搜索他们正在寻找的内容,如果找到了它会更改标签的内容。(实例)` Button = btn_Search
Textbox = InputBox
RichTextBox = rtb
Label = Results`
我想要做的是让用户可以在文本框中输入然后单击一个按钮,它会在 Richtextbox 中搜索他们正在寻找的内容,如果找到了它会更改标签的内容。(实例)` Button = btn_Search
Textbox = InputBox
RichTextBox = rtb
Label = Results`
另一种更干净的文本搜索方法如下,但首先您需要将 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 替换为下面的任何人,
不区分大小写
正则表达式 searchterm = new Regex(word,RegexOptions.IgnoreCase);
全词搜索
正则表达式 searchterm = new Regex(@"\b"+word+"\b");
不区分大小写和全字搜索
正则表达式 searchterm = new Regex(@"\b"+word+"\b",RegexOptions.IgnoreCase);
还有一件事,Regex搜索默认区分大小写。
使用此方法,在您的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";
}