Split Csv Line with regex - CSharp System.Text.RegularExpressions

CSharp examples for System.Text.RegularExpressions:Split String

Description

Split Csv Line with regex

Demo Code


using System.Linq;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

public class Main{
        // splits a CSV row 
   static public string[] SplitCsvLine(string line)
   {//from w w  w .  ja v a 2 s .  c  o  m
      string pattern = @"
          # Match one value in valid CSV string.
          (?!\s*$)                                      # Don't match empty last value.
          \s*                                           # Strip whitespace before value.
          (?:                                           # Group for value alternatives.
            '(?<val>[^'\\]*(?:\\[\S\s][^'\\]*)*)'       # Either $1: Single quoted string,
          | ""(?<val>[^""\\]*(?:\\[\S\s][^""\\]*)*)""   # or $2: Double quoted string,
          | (?<val>[^,'""\s]*(?:\s+[^,'""\s]+)*)          # or $3: Non-comma, non-quote stuff.
          )                                             # End group of value alternatives.
          \s*                                           # Strip whitespace after value.
          (?:,|$)                                       # Field ends on comma or EOS.
          ";

      //[^,'""\s] ??? , ' " \s ????????

      string[] values = (from System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(
                     line
                     , pattern
         , System.Text.RegularExpressions.RegexOptions.ExplicitCapture | System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                         select m.Groups[1].Value).ToArray();

      return values;
   }
}

Related Tutorials