2013-08-31 30 views
-2

我的程序應該找到在源文本框中Console.WriteLine("並開始閱讀字符串只是"後,直到它找到一個"),然後存儲在變量中捕獲的字符串。例如,如果輸入是:實現一個簡單的C#代碼解析器

Console.WriteLine("Hello World") 

然後變量的值應該是Hello World

幫助將不勝感激。

+0

編輯你的問題正確。 –

+0

@NikhilAgrawal我懂了 –

+0

這可能對你有用:http://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments – Matthew

回答

2
string yourInput = ... 
var result = Regex.Match(yourInput, "Console.WriteLine[(]\"(.*?)(?<!\\\\)\"[)]").Groups[1].Value; 

一個小測試:

string yourInput = "Console.WriteLine(\"\\\") Yeahhh\")"; 
yourInput += "Console.WriteLine(\"At least Regex can handle \"this\"\")"; 
yourInput += "Console.WriteLine(\"Although \"Regex\" is afraid of parsing \"text\" with nested elements\")"; 
var matches = Regex.Matches(yourInput, "Console.WriteLine[(]\"(.*?)(?<!\\\\)\"[)]"); 
foreach (Match m in matches) 
    System.Diagnostics.Debug.Print(m.Groups[1].Value); 

輸出

\") Yeahhh 
At least Regex can handle "this" 
Although "Regex" is afraid of parsing "text" with nested elements 
+0

'Console.WriteLine(「\」)Yeahhh「)」' - 正則表達式很難:) –

+0

@AlexeiLevenkov你是說該字符串無法與'Regex'匹配?我測試了它,結果是:) –

+0

但它應該是'\「)Yeahhh'(抱歉,我輸入'''而不是最後一個';':'Console.WriteLine(」\「)Yeahhh」); ') –