I realize this question has been asked many times here. I have looked at and tried many of the answers but none of them work for me.
I am creating an application using C# that can accept command line arguments. e.g.
- Start -p:SomeNameValue -h
- DisplayMessage -m:Hello
- DisplayMessage -m:'Hello World'
- DisplayMessage -m:"Hello World"
My args come in as a single string. I need to split by spaces except where there are single or double quotes. So the above would end up as
- Start- -p:SomeNameValue- -h
- DisplayMessage- -m:Hello
- DisplayMessage- -m:'Hello World'
- DisplayMessage- -m:"Hello World"
The answers I have found on here seem to break. e.g. They remove the : character or just don't work at all. Some of the code I've tried as follows:
var res1 = Regex.Matches(payload, @"[\""].+?[\""]|[^ ]+")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToList();
var res2 = payload.Split('"')
    .Select((element, index) => index % 2 == 0  
        ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
        : new string[] { element })  // Keep the entire item
    .SelectMany(element => element).ToList();
var res3 = Regex
    .Matches(payload, @"\w+|""[\w\s]*""")
    .Cast<Match>()
    .Select(m => m.Groups["match"].Value)
    .ToList();
string[] res4 = Regex.Split(payload, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
Regex regex = new Regex(@"\w+|""[\w\s]*""");
var res5 = regex.Matches(payload).Cast<Match>().ToList();
I simply want to split the arg into blocks as per above.
 
     
     
    