Question

I have a string like this:

string subjectString = "one two \"three four\" five \"six seven\"";

and I want to transform it into a StringCollection like this:

  • one
  • two
  • three four
  • five
  • six seven

Is there a way how to achieve this using a Regex class in asp.net C# 2.0, somehow like this way?

  string subjectString = "one two \"three four\" five \"six seven\"";
  System.Collections.Specialized.StringCollection stringCollection = new System.Collections.Specialized.StringCollection();
  foreach (System.Text.RegularExpressions.Match match in System.Text.RegularExpressions.Regex.Matches(subjectString, "some_regex_here"))  
  {  
    stringCollection.Add(match.Value);  
  }
Was it helpful?

Solution 2

I could only come up with the following regex pattern:

(?:"(.+?)")|(\w+?)(?:\s|$)

It's not perfect. Too lazy to test on all sort of string combinations, but I tried applying the pattern on your string and it returns exactly like what you expected.

P/S: I only tested it using RegexBuddy, not inside .Net codes.

OTHER TIPS

What you have is CSV using spaces as a separator, so you could just use a CSV parser:

var subjectString = "one two \"three four\" five \"six seven\"";

using (var csvReader = CsvReader.FromCsvString(subjectString))
{
    csvReader.ValueSeparator = ' ';
    csvReader.ValueDelimiter = '"';

    while (csvReader.HasMoreRecords)
    {
        var record = csvReader.ReadDataRecord();
        Console.WriteLine(record[2]);
    }
}

Output is "three four".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top