我需要突出显示.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;
}
}
问题是,它没有突出显示与正则表达式匹配的一些单词。有些是突出显示,但有些则不是。准确性是我的问题,我不知道我哪里出错。
答案 0 :(得分:1)
我检查了你的代码,其中有一些问题,我在下面列出:
第一:
for (int i = 0; i < dtXLS.Rows.Count; i++)
{
string[] wordsToRedact = new string[dtXLS.Rows.Count];
...
错误,你应该在for循环之前初始化你的字符串数组,否则它会在每次循环迭代中更新,执行以下操作:
string[] wordsToRedact = new string[listBox1.Items.Count];
for (int i = 0; i < dtXLS.Rows.Count; i++)
{
...
第二:(你的主要问题)rtb.SelectionStart = e.index;
rtb.SelectionLength = e.length;
rtb.SelectionBackColor = Color.LightSkyBlue;
和最后:(有疑问) 我想但我不确定你应该使用索引零[0]而不是[1]
public WordsToRedact(Match m)
{
this.index = m.Groups[0].Index;
this.length = m.Groups[0].Length;
this.value = m.Groups[0].Value;
}
答案 1 :(得分:0)
这将有效:
Regex test = new Regex(@"\b(" + wordsToRedact[i] + @")\b",
RegexOptions.Singleline | RegexOptions.Compiled);
答案 2 :(得分:0)
mahdi-tahsildari的回答确实回答了我的问题!但除了他的答案,我还想发布我尝试过的其他选项,也解决了问题。
我将HighLighting类更改为以下代码:
class HighLighting
{
public void HighlightText(RichTextBox rtb, string word)
{
int s_start = rtb.SelectionStart, startIndex = 0, index;
while ((index = rtb.Text.IndexOf(word, startIndex)) != -1)
{
rtb.Select(index, word.Length);
rtb.SelectionBackColor = Color.Yellow;
startIndex = index + word.Length;
}
rtb.SelectionStart = s_start;
rtb.SelectionLength = 0;
rtb.SelectionColor = Color.Black;
rtb.ScrollToCaret();
}
}
一切都很好。这段代码和mahdi-tahsildari的回答做了同样的事情!感谢你的帮助! :))