拆分字符串,同时保留用引号括起来的值(.NET)

时间:2010-07-05 22:34:17

标签: .net

我正在寻找一种方法,在.NET中,分割字符串,同时忽略引号(或另一个分隔符)内的分割字符。 (如果拆分分隔符是逗号,此功能将与典型的CSV解析器相匹配。)我不确定为什么此功能未内置到String.Split()中。

4 个答案:

答案 0 :(得分:5)

您可以使用正则表达式。例如:

string test = @"this,i""s,a"",test";
string[] parts =
  Regex.Matches(test, @"(""[^""]*""|[^,])+")
  .Cast<Match>()
  .Select(m => m.Value)
  .ToArray();

foreach (string s in parts) Console.WriteLine(s);

输出:

this
i"s,a"
test

答案 1 :(得分:1)

在这篇文章中查看Marc的答案:

Input array is longer than the number of columns in this table. Exception

他提到了一个可以用来做这个的图书馆。

答案 2 :(得分:0)

使用@ Guffa的方法,这是我的完整解决方案:

/// <summary>
/// Splits the string while preserving quoted values (i.e. instances of the delimiter character inside of quotes will not be split apart).
/// Trims leading and trailing whitespace from the individual string values.
/// Does not include empty values.
/// </summary>
/// <param name="value">The string to be split.</param>
/// <param name="delimiter">The delimiter to use to split the string, e.g. ',' for CSV.</param>
/// <returns>A collection of individual strings parsed from the original value.</returns>
public static IEnumerable<string> SplitWhilePreservingQuotedValues(this string value, char delimiter)
{
    Regex csvPreservingQuotedStrings = new Regex(string.Format("(\"[^\"]*\"|[^{0}])+", delimiter));
    var values =
        csvPreservingQuotedStrings.Matches(value)
        .Cast<Match>()
        .Select(m => m.Value.Trim())
        .Where(v => !string.IsNullOrWhiteSpace(v));
    return values;
}

答案 3 :(得分:0)

如果您还想允许单引号('),则将表达式更改为@“(”“[”“”] “”|'[^'] '| [^ \ s ])+”。

如果要从字符串中删除引号,请将Select更改为.Select(m =&gt; m.Value.Trim(new char [] {'\'','''}))。