我需要突出显示 .xls 文件中列出的richtextBox 中的所有单词,这是我的代码的一部分:
public void HighlightWords(RichTextBox rtb1, DataTable dtXLS)
{
for (int i = 0; i < dtXLS.Rows.Count; i++)
{
string[] wordsToRedact = new string[dtXLS.Rows.Count];
wordsToRedact[i] = dtXLS.Rows[i][0].ToString();
Regex test = new Regex(@"[\p{P}|\s](" + wordsToRedact[i] + @")[\p{P}|\s]", RegexOptions.Singleline | RegexOptions.Compiled);
MatchCollection matchlist = test.Matches(rtb1.Text);
if (matchlist.Count > 0)
{
for (int j = 0; j < matchlist.Count; j++)
{
WordsToRedact words = new WordsToRedact(matchlist[j]);
HighLighting highLight = new HighLighting();
highLight.Highlight_Words(rtb1, words);
}
}
}
}
class HighLighting
{
public void Highlight_Words(RichTextBox rtb, WordsToRedact e)
{
rtb.SelectionBackColor = Color.LightSkyBlue;
rtb.SelectionStart = e.index;
rtb.SelectionLength = e.length;
rtb.ScrollToCaret();
}
}
class WordsToRedact
{
public int index;
public int length;
public string value;
public WordsToRedact(Match m)
{
this.index = m.Groups[1].Index;
this.length = m.Groups[1].Length;
this.value = m.Groups[1].Value;
}
}
问题是,它没有突出显示一些也与正则表达式匹配的单词。有些被突出显示,但有些没有。准确性是我的问题,我不知道我哪里错了。