0

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);  
  }
svick
  • 236,525
  • 50
  • 385
  • 514

2 Answers2

3

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".

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • Hello Kent, thank you very much for you help. It is almost what I need, I yet need this to work with the 2.0 version of .Net Framework. Cheers. – user2323457 Apr 26 '13 at 11:10
0

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.

ajakblackgoat
  • 2,119
  • 1
  • 15
  • 10