首页 > 解决方案 > 用引号解析命令行参数

问题描述

好的,所以我用空格吐出命令行参数,比如命令提示符,但问题是,如果用户尝试输入 DoStuff“有空格但被引用的参数”,它将无法正确拆分。我正在使用控制台应用程序。我试过这样做:baseCommand 是用户输入未解析的字符串,而 secondCommand 应该是第二个参数。

int firstQuoteIndex = baseCommand.IndexOf('"');

if (firstQuoteIndex != -1)
{
    int secondQuoteIndex = baseCommand.LastIndexOf('"');
    secondCommand = baseCommand.Substring(firstQuoteIndex, 
        secondQuoteIndex - firstQuoteIndex + 1).Replace("\"", "");
}

这很好用,但首先,它很乱,其次,如果用户输入如下内容,我不确定如何执行此操作:

DoSomething "second arg that has spaces" "third arg that has spaces"

请记住,如果 arg(s) 没有引号,则用户不必输入引号。有人有什么建议吗,谢谢。

标签: c#parsingcommand-lineconsolearguments

解决方案


您可以为此目的使用以下正则表达式。

[\""].+?[\""]|[^ ]+

例如,

var commandList = Regex.Matches(baseCommand, @"[\""].+?[\""]|[^ ]+")
                .Cast<Match>()
                .Select(x => x.Value.Trim('"'))
                .ToList();

样本 1 输入

DoSomething "second arg that has spaces" thirdArgumentWithoutSpaces

输出

Command List
------------
DoSomething 
second arg that has spaces
thirdArgumentWithoutSpaces

样本 2 输入

DoSomething "second arg that has spaces" "third Argument With Spaces"

输出

Command List
------------
DoSomething 
second arg that has spaces
third Argument With Spaces

推荐阅读