代码之家  ›  专栏  ›  技术社区  ›  Pat

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

  •  2
  • Pat  · 技术社区  · 15 年前

    String.Split() .

    4 回复  |  直到 15 年前
        1
  •  5
  •   Guffa    15 年前

    你可以用正则表达式。例子:

    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
    
        2
  •  1
  •   Community CDub    8 年前

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

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

        3
  •  0
  •   Pat    15 年前

    使用@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;
    }
    
        4
  •  0
  •   Brad    10 年前

    “|[^\s])+”。

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