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

问题描述 投票:3回答:1

我有此代码根据与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");
c# parsing console-application
1个回答
0
投票

编辑更新!我想我找到了一种方法。我使用以下2种方法创建了一种方法:首先,该方法查找并返回嵌套的字符串,以用于循环/ 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个命令时刻“打印”和“循环”:

© www.soinside.com 2019 - 2024. All rights reserved.