-4

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?

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Bruno Klein
  • 3,217
  • 5
  • 29
  • 39

1 Answers1

3

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

Shar1er80
  • 9,001
  • 2
  • 20
  • 29