2015-05-02 122 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,因爲你的建議實際上給了我這個主意!