如何将这个特定的字符串拆分成数组

How split this specific string into array

如何将带有空格的特定字符串拆分为数组?
MyDatabase C:\MyDatabase\Backup "C:\Program Files\MySQL\MySQL Server 8.0\bin"
我想要这样的数组:\

[MyDatabase], [C:\MyDatabase\Backup], ["C:\Program Files\MySQL\MySQL Server 8.0\bin"]


我无法为 .Split() 函数匹配任何特定的运算符

 var s=@"mydbbb D:\mssql ""C:\Program Files\MySQL\MySQL Server 8.0\bin\""";

 Console.WriteLine(s.Split(' ')[0]);
 Console.WriteLine(s.Split(' ')[1]);

 int i = s.IndexOf(' ');
 i = s.IndexOf(' ', i + 1);
 Console.WriteLine(s.Substring(i));

试试这个

var path = @"MyDatabase C:\MyDatabase\Backup ""C:\Program Files\MySQL\MySQL Server 8.0\bin""";
            var pattern = @"(?<FirstWord>\w+)\s(?<Path1>.*)\s(?<Path2>\"".*\"")";
            Debug.WriteLine(path);
            Regex rgx = new Regex(pattern);
            Match match = rgx.Match(path);
            if (match.Success)
                ShowMatches(rgx, match);

private static void ShowMatches(Regex r, Match m)
        {
            string[] names = r.GetGroupNames();
            Debug.WriteLine("Named Groups:");
            foreach (var name in names)
            {
                Group grp = m.Groups[name];
                Debug.WriteLine("   {0}: '{1}'", name, grp.Value);
            }
        }

如果您正在编写代码来解析 command-line 个参数,您可以使用 the NuGet package System.CommandLine.

添加那个包后,你可以这样写代码:

using System;
using System.CommandLine;

namespace Demo
{
    static class Program
    {
        static void Main()
        {
            string commandLine = "MyDatabase C:\MyDatabase\Backup \"C:\Program Files\MySQL\MySQL Server 8.0\bin\"";

            var cmd    = new RootCommand();
            var result = cmd.Parse(commandLine);

            Console.WriteLine($"{result.Tokens.Count} arguments found:");

            foreach (var argument in result.Tokens)
            {
                Console.WriteLine(argument);
            }
        }
    }
}

该程序的输出是:

3 arguments found:
Argument: MyDatabase
Argument: C:\MyDatabase\Backup
Argument: C:\Program Files\MySQL\MySQL Server 8.0\bin

这有点像“敲坚果的大锤”,但如果您真的要解析命令行参数,System.CommandLine 提供的功能远远超出基本解析。