解析带引号的命令行参数

Vis*_*ser 2 c# console command-line parsing arguments

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

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

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

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

DoSomething "second arg that has spaces" "third arg that has spaces"
Run Code Online (Sandbox Code Playgroud)

请记住,如果参数没有引号,则用户不必输入引号。有没有人有什么建议,谢谢。

Anu*_*wan 9

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

[\""].+?[\""]|[^ ]+
Run Code Online (Sandbox Code Playgroud)

例如,

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

示例 1 输入

DoSomething "second arg that has spaces" thirdArgumentWithoutSpaces
Run Code Online (Sandbox Code Playgroud)

输出

Command List
------------
DoSomething 
second arg that has spaces
thirdArgumentWithoutSpaces
Run Code Online (Sandbox Code Playgroud)

示例 2 输入

DoSomething "second arg that has spaces" "third Argument With Spaces"
Run Code Online (Sandbox Code Playgroud)

输出

Command List
------------
DoSomething 
second arg that has spaces
third Argument With Spaces
Run Code Online (Sandbox Code Playgroud)