在richtextbox中查找单词 [英] Find words in richtextbox
本文介绍了在richtextbox中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码在richtext框中搜索文本:
I'm using the following code to search for text in a richtext box:
richTextBox1.Find(textBox1.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
如果我输入:
textbox1:int
richtextbox1内容突出显示如下:
if I input:
textbox1 : int
the richtextbox1 content is highlighted like below:
richtextbox1: You are intelligent but intimidating
但我希望突出显示如下相同的输入in textbox1:
but I want the highlighting to be as follows for the same input in textbox1 :
You are intelligent but intimidating.
请指教..谢谢..
Please advice.. Thank you..
推荐答案
private void button1_Click(object sender, EventArgs e)
{
selectWords(richTextBox1.Text, textBox1.Text);
}
private void selectWords(string fullText, string searchText)
{
string[] words = fullText.Split(' ');
foreach (var word in words)
{
if (word.Contains(searchText))
{
richTextBox1.Find(word, 0, richTextBox1.TextLength, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Green;
}
}
}
我不知道确切原因solution1没有突出显示实际的searchtext。可能每次使用零(0)作为find方法的起始索引。因此我修改如下。
Hi,
I dont know the exact reason why solution1 is not highlighting actual searchtext. May be using every time zero(0) as starting index in find method. Hence i modified as below.
string[] words = fullText.Split(' ');
int index = 0;
foreach (var word in words)
{
if (word.Contains(searchText))
{
index = richTextBox1.Find(word, index, richTextBox1.TextLength, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Green;
index++;
}
}
你可以尝试正则表达式
这个表达式只适用于小写字母。
You can try regular expression
This expression will only work for lower case letters.
textBox1.Text = @"int\w*";
这是表格中的假定功能
This is an assumed function in your Form
private void buttonHighLight_Click(object sender, EventArgs e)
{
// If the input contains the regular expression part
HighLightWords(textBox1.Text);
// or if you don't want the user to deal with regular expressions, you can add this part in code.
HighLightWords(String.Format(@"{0}\w*", textBox1.Text);
}
这将突出显示与输入表达式匹配的任何单词。
This will highlight any word that matches the input expression.
private void HighLightWords(string wordExpression)
{
Regex regex = new Regex(wordExpression, RegexOptions.CultureInvariant | RegexOptions.Singleline);
foreach (Match m in regex.Matches(richTextBox1.Text))
{
richTextBox1.SelectionStart = m.Index;
richTextBox1.SelectionLength = m.Length;
richTextBox1.SelectionBackColor = Color.Yellow;
}
}
这篇关于在richtextbox中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文