0

我有一个这样的字符串:

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

我想将它转换成这样的 StringCollection:

  • 三四
  • 六七

有没有办法在 asp.net C# 2.0 中使用 Regex 类来实现这一点,就像这样?

  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);  
  }
4

2 回答 2

3

您所拥有的是使用空格作为分隔符的 CSV,因此您可以只使用CSV 解析器

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]);
    }
}

输出为“三四”。

于 2013-04-26T10:56:04.970 回答
0

我只能想出以下正则表达式模式:

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

这并不完美。懒得测试各种字符串组合,但我尝试在你的字符串上应用模式,它返回的结果完全符合你的预期。

P/S:我只使用 RegexBuddy 对其进行了测试,而不是在 .Net 代码中进行了测试。

于 2013-04-26T11:47:39.337 回答