Regular Expression to split on spaces unless in quotes

.net, c#, regex

Solution

No options required

Regex:

\w+|"[\w\s]*"

C#:

Regex regex = new Regex(@"\w+|""[\w\s]*""");

Or if you need to exclude " characters:

    Regex
        .Matches(input, @"(?<match>\w+)|\""(?<match>[\w\s]*)""")
        .Cast<Match>()
        .Select(m => m.Groups["match"].Value)
        .ToList()
        .ForEach(s => Console.WriteLine(s));

Problem

I would like to use the .Net Regex.Split method to split this input string into an array. It must split on whitespace unless it is enclosed in a quote. Input: Here is "my string" it has "six matches" Expected output: - Here - is - my string - it - has - six matches What pattern do I need? Also do I need to specify any RegexOptions?

Original source

Related problems