【问题标题】:Parsing string commands for a basic scripting language解析基本脚本语言的字符串命令
【发布时间】:2013-04-05 00:37:56
【问题描述】:

我正在尝试解释字符串命令以运行相关脚本。这是我目前所拥有的:

        // A typical command that can come from a TextBox control
        string command = "Create";

        // Remove all white space
        command = System.Text.RegularExpressions.Regex.Replace(command, @"\s", "");

        // Make case insesitive by converting to lowercase
        command = command.ToLower();

        switch (command)
        {
            case "create": /* Run create script*/ break;
            case "delete": /* Run delete script*/ break;
            // etc.
        }

在我引入与特定命令相关的参数之前,这很好用。

我认为这可以用圆括号表示,因此更复杂的命令如下所示:

string command = "Create(paramA, paramB, etc.)"

假设我使用这种方法走在正确的道路上,那么检测和解释参数的好方法是什么?

命令的规则是:

'(' ')' 打开和关闭参数集 ',' 分隔每个参数

换句话说,如何检测参数的开头和结尾并正确分隔每个参数?

另一个问题当然是将命令本身与参数分开。

我考虑过使用:

command.StartsWith("create"); // etc.

但这在 switch case 条件结构中不起作用。

【问题讨论】:

  • 你可以使用大量的字符串魔法,这是可能的,但需要努力。或者您可以查看现有的解析框架,例如 Sprache:github.com/sprache/sprache
  • 解析。那是我正在寻找的关键字。我将更新问题的标题。谢谢。

标签: c# string parsing scripting


【解决方案1】:

您必须创建一个解释器类,它将命令分成单独的部分,存储在Command 类中。例如,您可以打开 Command.Name。

一些伪代码来表明我的意思:

public static class Interpreter
{
    public static Command CreateCommand(string commandLine)
    {
        Command newCommand = new Command();
        newCommand.Name = commandLine.Split(' ')[0];
        newCommand.Parameters.Add(...)

        return newCommand
    } 
}

您当然必须准确检查命令行的语法。命令类存储有关命令的信息,例如它的名称、参数列表、返回类型等。

一旦您有了Command 对象,您就可以在适用的情况下对它的任何属性执行switch 语句。稍后,您可以编写方法来执行命令并将所有信息整齐地存储,而无需再次解释它。

【讨论】:

    【解决方案2】:

    在您的代码中只需更改

    开关(命令)

    switch (command.Substring(0, command.IndexOf('(')))

    参数用','分割

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      相关资源
      最近更新 更多