REGEX Expression C#. Split string by whitespace outside the quotation marks



I'm trying to define a regular expression for the Split function in order to obtain all substring split by a whitespace omitting those whitespaces that are into single quotation marks.


key1:value1 key2:'value2 value3'

i Need these separated values:

  • key1:value1

  • key2:'value2 value3'

I'm tried to perform this in different ways:

  • Regex.Split(q, @"(\s)^('\s')").ToList();
  • Regex.Split(q, @"(\s)(^'.\s.')").ToList();
  • Regex.Split(q, @"(?=.*\s)").ToList();

What i am wrong with this code?

Could you please help me with this?

Thanks in advance

3 Answers: 

    var st = "key1:value1 key2:'value2 value3'";
     var result = Regex.Matches(st, @"\w+:\w+|\w+:\'[^']+\'");

    foreach (var item in result)

The result should be:

key2:'value2 value3'

A working example:


(\w+)       # key: 1 or more word chars (captured)
:           # literal
(?:         # non-captured grouped alternatives
(\w+)       # value: 1 or more word chars (captured)
|           # or
'([^']+)'   # 1 or more not "'" enclosed by "'" (captured)
)           # end of group


Your try:


^ means beginning of line, \s is a white-space characters. If you want to use the not-operator, this only works in a character class [^\s] -> 1 character not a white-space.


Try following :

       static void Main(string[] args)
            string input = "key1:value1 key2:'value2 value3'";
            string pattern = @"\s*(?'key'[^:]+):((?'value'[^'][^\s]+)|'(?'value'[^']+))";

            MatchCollection matches = Regex.Matches(input, pattern);
            foreach (Match match in matches)
                Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);