2015-05-02 53 views
0

因此,我一直在Visual Studio 2013中使用C#编写脚本编辑器,当然我想要将语法突出显示作为功能。 我有以下代码:语法突出显示不能正常工作

programTextBox.Enabled = false; 
Regex cKeyWords = new Regex("(auto|break|case|char|const|continue|defaut|double|else|enum|extern|float|for|goto|if|int" + 
          "|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)"); 
int selectStart = this.programTextBox.SelectionStart; 
int programCurrentLine = programTextBox.GetLineFromCharIndex(programTextBox.SelectionStart); 
MatchCollection matches = cKeyWords.Matches(programTextBox.Lines[programCurrentLine].ToString()); 
foreach (Match match in matches) 
{ 
    programTextBox.Select(match.Index, match.Length); 
    programTextBox.SelectionColor = Color.Blue; 
} 
programTextBox.Select(selectStart, 0); 
programTextBox.SelectionColor = Color.Black; 
programTextBox.Enabled = true; 

那么,它有什么作用?它在当前行中搜索一些特定的单词。并且形成我的测试,我可以说它实际上可以在几毫秒内找到这些单词。

但它并没有真正的工作。找到匹配后,它会更改第一行的颜色。我的意思是?这是一个例子。 Let'say,我用我的脚本编辑器来编写代码:

#include <stdio.h> 
int main(){ 
    ... 
} 

在这段代码中,int是关键字,因此它必须成为蓝色。但是,第一行的前三个字母变成蓝色。我还应该提到,这个例子int在第二行的开头,这就是为什么第一行的前三个字符改变的原因。

所以,我的代码可以找到关键字,并且可以找到它们的位置,但不是更改这些词的颜色,而是应用第一行中的更改。

有人可以提供解决方案吗?

编辑:我找到了解决这个问题的方法。在下面简单检查我的答案。

+2

Match.Index是错误的,这就是* regex *单*行中单词的索引。您必须添加您正在解析的行的索引。 –

+0

此外,使用正则表达式解析并不是你应该做的。使用解析器/词法分析器,如ANTLR。 –

+0

@HansPassant我应该怎么做到这一点?我尝试用programTextBox.GetFirstCharIndexOfCurrentLine()替换match.Index。但是,它只会突出显示每行的第一个关键字。如果同一行有多个关键字,则其余的关键字不会改变其颜色。 –

回答

0

我真的找到了解决这个问题的方法!

foreach (Match match in matches) 
{ 
    programTextBox.Select(programTextBox.GetFirstCharIndexOfCurrentLine() + match.Index, match.Length); 
    programTextBox.SelectionColor = Color.Blue; 
} 

(代码的其余部分实际上是一样的。)

汉斯帕桑特实际上是正确的,match.Index是造成问题。玩了一番,并从一些帮助的意见后,我发现使用programTextBox.GetFirstCharIndexOfCurrentLine()+ match.Index解决了这个问题。

为什么?与programTextBox.GetFirstCharIndexOfCurrentLine()我可以知道在哪一行我必须改变颜色和match.Index我可以知道在当前行的哪里是找到的关键字。

无论如何,我想感谢你Hans Passant,因为你的建议实际上给了我这个主意!