0

How can i split this specific string with spaces into array?
MyDatabase C:\MyDatabase\Backup "C:\Program Files\MySQL\MySQL Server 8.0\bin"
I want to have array like this: \

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


I can't match any specific sperator for .Split() function

MTS
  • 104
  • 7
  • 1
    You can use ("[^"]+")|[^ ]+ as regex pattern. – Xiang Wei Huang Jan 26 '22 at 09:27
  • 1
    It's effectively a CSV with space as the delimiter instead of a comma. Don't reinvent CSV parsing, just use one that exists and lets you set a delimiter. If you don't want to go for that, write a simple finite state machine to do the parsing; read the line char by char - you're either boolean "inside a `"` quote" or you're "not inside a quote" so toggle the boolean every time you encoutner a quote. If you are not inside_a_quote and you encounter a space, then take a chunk of string from the current position back to the last place you took a chunk – Caius Jard Jan 26 '22 at 09:30
  • @Luuk not really – MTS Jan 26 '22 at 09:39
  • 1
    Look at Mark Bracektt's answer in https://stackoverflow.com/questions/959448/split-csv-string - it's VB but it's readable to a C# developer because it's trivial: Char at a time, examine it, toggling if it's a quote. It's quite inefficient in that it concats the char onto a string if it's neither a delimiter nor quote, so I'd tweak it to just have an int variable that remembers the location of the last split, and substring from there when an addition to the list is required.. – Caius Jard Jan 26 '22 at 09:44
  • 1
    Or I'd use a stringbuilder instead of a string, and concat the chars into that, tostringing and clearing it whenever a word is added to the list – Caius Jard Jan 26 '22 at 09:47
  • For an example, using the regular expression from @XiangWeiHuang, see: https://dotnetfiddle.net/R4B8ll – Luuk Jan 26 '22 at 10:04
  • The regexp goes funny if user inputs some funky pattern though. e.g. " """ and it captures 2 results: " " and "". Check on regex101. The substring method @CaiusJard mentioned should be more stable. – Xiang Wei Huang Jan 27 '22 at 01:21

3 Answers3

1

If you are writing code to parse command-line arguments, you could use the NuGet package System.CommandLine.

After adding that package, you can write code like this:

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);
            }
        }
    }
}

The output from that program is:

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

This is somewhat of a "sledgehammer to crack a nut", but if you really are parsing command line arguments, System.CommandLine provides a great deal of functionality beyond just the basic parsing.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
-1
 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));
Amjad S.
  • 1,196
  • 1
  • 4
  • 16
  • I can't edit the string :x `"mydbbb D:\\mssql \"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\""` – MTS Jan 26 '22 at 09:41
  • var s=@"mydbbb D:\\mssql ""C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\"""; Just replace the /" by "" and add @ at the beginning of string. – Amjad S. Jan 26 '22 at 10:20
-1

Try this

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);
            }
        }