[英]Highlight text in a RichTextBox Control
我试图在 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 的文本进行匹配。
Matches 集合中的每个Match都包含找到匹配的索引(文本内的位置)和它的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.