Regex for splitting a string using space when not surrounded by single or double quotes

后端 未结 15 2380
梦毁少年i
梦毁少年i 2020-11-22 03:15

I\'m new to regular expressions and would appreciate your help. I\'m trying to put together an expression that will split the example string using all spaces that are not s

15条回答
  •  Happy的楠姐
    2020-11-22 03:36

    The following returns an array of arguments. Arguments are the variable 'command' split on spaces, unless included in single or double quotes. The matches are then modified to remove the single and double quotes.

    using System.Text.RegularExpressions;
    
    var args = Regex.Matches(command, "[^\\s\"']+|\"([^\"]*)\"|'([^']*)'").Cast
    ().Select(iMatch => iMatch.Value.Replace("\"", "").Replace("'", "")).ToArray();
    

提交回复
热议问题