实现一个简单的C#代码解析器

本文关键字:代码 简单 一个 实现 | 更新日期: 2023-09-27 18:29:46

我的程序应该在源文本框中找到Console.WriteLine(",并在"之后开始读取字符串,直到找到"),然后将捕获的字符串存储在变量中。例如,如果输入为:

Console.WriteLine("Hello World")

那么变量的值应该是Hello World

我们将不胜感激。

实现一个简单的C#代码解析器

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