Search code examples
c#regexdouble-quotes

Regex. Spliting os blank spaces. Accounting for double quoted text


I am using regex to split a string. This is the input: Value1 Value2 "Val ue3"

The output should be:

  • Value1

  • Value2

  • Val ue3

What regex should be using for this?


Solution

  • You can try this pattern:

    "\\w+|\"[\\w ]+\""
    

    It'll match words and words with spaces in between quotes. Since your output indicates you want the quotes removed then a String.Replace() can take care of that.

    using System;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        public static void Main()
        {
            string data = "Value1   Value2   \"Val ue3\"";
            MatchCollection matchCollection = Regex.Matches(data, "\\w+|\"[\\w ]+\"");
            foreach (Match match in matchCollection)
            {
                Console.WriteLine(match.Value.Replace("\"", String.Empty));
            }
        }
    }
    

    Results:

    Value1
    Value2
    Val ue3
    

    Fiddle Demo