gpt4 book ai didi

c# - 如何使用预定义标记列表实现解析器/解释器?

转载 作者:行者123 更新时间:2023-12-05 07:10:09 26 4
gpt4 key购买 nike

我有这段代码可以根据与 Regex 匹配的内容以字符串形式生成标记:

public static List<Tuple<string, string>> GetTokens(string input)
{
List<Tuple<string, string>> ret = new List<Tuple<string, string>>();
Regex r = new Regex("(?<Comma>\\,)" +
"|(?<Dot>\\.)" +
"|(?<SemiColon>\\;)" +
"|(?<DoubleDot>\\:)" +
"|(?<Increment>\\+\\+)" +
"|(?<greater>\\>)" +
"|(?<smaller>\\<)" +
"|(?<Decrement>\\-\\-)" +
"|(?<SystemCommand> *deviceListCount *| *deviceList *| *devices *| *device *| *str *| *int *| *dev *| *bool *| *print *| *wait *| *device *| *if *| *while *| *loop *)" +
"|(?<OpenBracket>\\()" +
"|(?<CloseBracket>\\))" +
"|(?<DeviceCommand> *On *| *Off *| *Open *| *Close *| *Move *| *Detect *)" +
"|(?<Integer>\\d+)"+
"|(?<equals> *[=] *)" +
"|(?<String>[aA-zZ0-9 ]*)");
foreach (Match item in r.Matches(input))
{
for (int i = 1; i < item.Groups.Count; i++)
{
string v = item.Groups[i].Value;
if (v != "")
{
ret.Add(new Tuple<string, string>(r.GroupNameFromNumber(i), v));
}
}
}
return ret;
}

从简单开始,我如何使用上面的方法创建一个打印命令:

print(hello world)

我想用这样的方式运行代码:

RunCode(GetTokens("print(Hello World)"))

此代码应产生与以下相同的效果:

Console.WriteLine("Hello World");

最佳答案

编辑更新!我想我找到了一种方法。我使用以下两种方法创建了一种方法:首先,此方法查找并返回嵌套字符串以用于循环/while 循环和 if 语句:

public static string UntilNestedEnd(List<Tuple<string, string>> t, ref int i)
{
string inner = "";
int nested = 0;
while (true)
{
if (i < t.Count-1)
{
i++;
if (t[i].Item2 == ")")
{
nested--;
if (nested > 0)
{
inner += t[i].Item2;
}
}
else if (t[i].Item2 == "(")
{
if (nested > 0)
{
inner += t[i].Item2;
}
nested++;
}
else
{
inner += t[i].Item2;
}
if (nested == 0)
{
break;
}
}
}
return inner;
}

这是可以执行命令的代码,我所要做的就是说在检索字符串之前应该跳过多少步,它导致嵌套语句似乎有效,到目前为止我只有 2 个命令“打印”和“循环”时刻:

public static void RunCode(string input)
{
var g = GetTokens(input);
for (int i = 0; i < g.Count; i++)
{
if (g[i].Item2 == "print")
{
Console.WriteLine(UntilNestedEnd(g, ref i));
}
else if (g[i].Item2 == "loop")
{
int cnt = int.Parse(g[i+2].Item2);
i +=2;
string nested = UntilNestedEnd(g,ref i);
for (int x = 0; x < cnt; x++)
{
RunCode(nested);
}
}
}
}

这是运行它的代码:

static void Main(string[] args)
{
RunCode("loop:2(loop:2(loop:2(print(hello))))");
Console.ReadLine();
}

关于c# - 如何使用预定义标记列表实现解析器/解释器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61356109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com