如何解决突出显示RichTextBox控件中的文本
我正在尝试突出显示RichTextBox中多行特定文本。
这是我突出显示文本的代码:
public void HighlightMistakes(RichTextBox richTextBox)
{
string[] phrases = { "Drivers Do Not Match","Current Does Not Match","No Drivers Found" };
foreach (var phrase in phrases)
{
int startIndex = 0;
while (startIndex <= richTextBox.TextLength)
{
int phraseStartIndex = richTextBox.Find(phrase,startIndex,RichTextBoxFinds.None);
if (phraseStartIndex != -1)
{
richTextBox.SelectionStart = phraseStartIndex;
richTextBox.SelectionLength = phrase.Length;
richTextBox.SelectionBackColor = Color.Yellow;
}
else break;
startIndex += phraseStartIndex + phrase.Length;
}
}
}
这是我向RTB添加文本并调用上面的函数的方式:
foreach (var a in resultList)
{
richTextBox1.AppendText("\n"+a + "\n");
HighlightMistakes(richTextBox1);
}
但是,HighlightMistakes
不能按我希望的方式工作。这样做的目的是突出显示phrases
数组中指定的所有字符串值,而并非每次都这样。
示例:
我不确定为什么跳过了某些行而没有跳过某些行。
解决方法
如果对简单的Regex方法没有任何帮助,则可以使用Regex.Matches将短语列表与RichTextBox的文本进行匹配。
匹配项集合中的每个Match都包含找到匹配项的Index(文本内的位置)及其Length,因此您只需调用.Select(Index,Length)即可选择一个短语并将其突出显示。
所使用的模式是将短语与管道(|
相匹配而产生的字符串。
由于文本中可能包含元字符,因此每个短语都传递给Regex.Escape()。
如果要考虑这种情况,请删除RegexOptions.IgnoreCase
。
using System.Text.RegularExpressions;
string[] phrases = { "Drivers Do Not Match","Current Does Not Match","No Drivers Found" };
HighlightMistakes(richTextBox1,phrases);
private void HighlightMistakes(RichTextBox rtb,string[] phrases)
{
ClearMistakes(rtb);
string pattern = string.Join("|",phrases.Select(phr => Regex.Escape(phr)));
var matches = Regex.Matches(rtb.Text,pattern,RegexOptions.IgnoreCase);
foreach (Match m in matches) {
rtb.Select(m.Index,m.Length);
rtb.SelectionBackColor = Color.Yellow;
}
}
private void ClearMistakes(RichTextBox rtb)
{
int selStart = rtb.SelectionStart;
rtb.SelectAll();
rtb.SelectionBackColor = rtb.BackColor;
rtb.SelectionStart = selStart;
rtb.SelectionLength = 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。