Reputation: 11
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:
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);
}
Upvotes: 0
Views: 115
Reputation: 2149
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.
Upvotes: 0
Reputation: 178660
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".
Upvotes: 3