3

我正在寻找创建类似 IRC 的命令格式:

/commandname parameter1 "parameter 2" "parameter \"3\"" parameter"4 parameter\"5

这将(理想情况下)给我一个参数列表:

parameter1
parameter 2
parameter "3"
parameter"4
parameter\"5

现在从我所读的内容来看,这根本不是微不足道的,也可以用其他方法来完成。

想法?

下面是完成我需要的工作的 C# 代码:

public List<string> ParseIrcCommand(string command)
    {
        command = command.Trim();
        command = command.TrimStart(new char[] { '/' });
        command += ' ';

        List<string> Tokens = new List<string>();

        int tokenStart = 0;
        bool inQuotes = false;
        bool inToken = true;
        string currentToken = "";
        for (int i = tokenStart; i < command.Length; i++)
        {
            char currentChar = command[i];
            char nextChar = (i + 1 >= command.Length ? ' ' : command[i + 1]);

            if (!inQuotes && inToken && currentChar == ' ')
            {
                Tokens.Add(currentToken);
                currentToken = "";
                inToken = false;
                continue;
            }

            if (inQuotes && inToken && currentChar == '"')
            {
                Tokens.Add(currentToken);
                currentToken = "";
                inQuotes = false;
                inToken = false;
                if (nextChar == ' ') i++;
                continue;
            }

            if (inQuotes && inToken && currentChar == '\\' && nextChar == '"')
            {
                i++;
                currentToken += nextChar;
                continue;
            }

            if (!inToken && currentChar != ' ')
            {
                inToken = true;
                tokenStart = i;
                if (currentChar == '"')
                {
                    tokenStart++;
                    inQuotes = true;
                    continue;
                }
            }

            currentToken += currentChar;
        }

        return Tokens;
    }
4

2 回答 2

4

您已经展示了您的代码 - 这很好,但您似乎没有考虑过这样解析命令是否合理:

  • 首先,您的代码将允许命令名称和参数中包含换行符。如果您假设换行符永远不会出现,那将是合理的。
  • 其次,\也需要像 一样进行转义,因为无法在参数末尾"指定单个而不引起任何混淆。\
  • 第三,将命令名称以与参数相同的方式解析有点奇怪——命令名称通常是自行确定和固定的,因此不需要灵活的方式来指定它。

我想不出 JavaScript 中通用的单行解决方案。JavaScript 正则表达式缺少\G,它断言最后一个匹配边界。因此,我的解决方案将不得不处理字符串断言的开头^并在匹配令牌时切掉字符串。

(这里代码不多,主要是注释)

function parseCommand(str) {
    /*
     * Trim() in C# will trim off all whitespace characters
     * \s in JavaScript regex also match any whitespace character
     * However, the set of characters considered as whitespace might not be
     * equivalent
     * But you can be sure that \r, \n, \t, space (ASCII 32) are included.
     * 
     * However, allowing all those whitespace characters in the command
     * is questionable.
     */
    str = str.replace(/^\s*\//, "");

    /* Look-ahead (?!") is needed to prevent matching of quoted parameter with
     * missing closing quote
     * The look-ahead comes from the fact that your code does not backtrack
     * while the regex engine will backtrack. Possessive qualifier can prevent
     * backtracking, but it is not supported by JavaScript RegExp.
     *
     * We emulate the effect of \G by using ^ and repeatedly chomping off
     * the string.
     *
     * The regex will match 2 cases:
     * (?!")([^ ]+)
     * This will match non-quoted tokens, which are not allowed to 
     * contain spaces
     * The token is captured into capturing group 1
     *
     * "((?:[^\\"]|\\[\\"])*)"
     * This will match quoted tokens, which consists of 0 or more:
     * non-quote-or-backslash [^\\"] OR escaped quote \"
     * OR escaped backslash \\
     * The text inside the quote is captured into capturing group 2
     */
    var regex = /^ *(?:(?!")([^ ]+)|"((?:[^\\"]|\\[\\"])*)")/;
    var tokens = [];
    var arr;

    while ((arr = str.match(regex)) !== null) {
        if (arr[1] !== void 0) {
            // Non-space token
            tokens.push(arr[1]);
        } else {
            // Quoted token, needs extra processing to
            // convert escaped character back
            tokens.push(arr[2].replace(/\\([\\"])/g, '$1'));
        }

        // Remove the matched text
        str = str.substring(arr[0].length);
    }

    // Test that the leftover consists of only space characters
    if (/^ *$/.test(str)) {
        return tokens;
    } else {
        // The only way to reach here is opened quoted token
        // Your code returns the tokens successfully parsed
        // but I think it is better to show an error here.
        return null;
    }
}
于 2013-02-06T17:46:07.223 回答
0

我创建了一个与您编写的命令行匹配的简单正则表达式。

/\w+\s((("([^\\"]*\\")*[^\\"]*")|[^ ]+)(\b|\s+))+$
  • /\w+\s找到命令的第一部分
  • (((
  • "([^\\"]*\\")*查找以"不包含\"后跟\"一个或多次的任何字符串(因此允许"something\""some\"thing\"依此类推
  • [^\\"]*"后跟一个不包含\or的字符列表",最后是一个"
  • )|[^ ]+这是另一种选择:查找任何非空格字符序列
  • )
  • (\b|\s+)所有跟随者由空格或单词边界
  • )+$一次或多次,每个命令一次,直到字符串结束

我担心这有时会失败,但我发布这个是为了表明有时参数具有基于重复的结构,例如查看"something\"something\"something\"end"重复结构在哪里something\",你可以使用这个想法来构建你的正则表达式

于 2013-02-06T13:31:37.560 回答