// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; using System.Text.RegularExpressions; class MainClass { public static void replaceandsplit(string s) { string[] s2 = s.Replace("\"","").Split(",".ToCharArray()); for(int i = 0; i < s2.Length; i++) { Console.WriteLine(" " + s2[i]); } } public static void splitandreplace(string s) { string[] s2 = s.Split(",".ToCharArray()); for(int i = 0; i < s2.Length; i++) { Console.WriteLine(" " + s2[i].Replace("\"","")); } } public static void manualparse(string s) { StringBuilder sb = new StringBuilder(); int ix = 0; bool inq = false; while(ix < s.Length) { switch(s[ix]) { case '"': if(inq) { if(((ix + 1) < s.Length) && (s[ix + 1] == '"')) { sb.Append(s[ix]); sb.Append(s[ix]); ix++; } else { inq = false; } } else { inq = true; } break; case ',': if(inq) { sb.Append(s[ix]); } else { Console.WriteLine(" " + sb.ToString()); sb = new StringBuilder(); } break; default: sb.Append(s[ix]); break; } ix++; } if(sb.Length > 0) { Console.WriteLine(" " + sb.ToString()); } } public static void regexparse(string s) { MatchCollection res = Regex.Matches(s,"([0-9]+)|([\"]{1}(([^\"])|(\"\"))*[\"]{1})"); for(int i = 0; i < res.Count; i++) { string s2 = res[i].Value; if(s2[0]=='"') { Console.WriteLine(" " + s2.Substring(1, s2.Length - 2)); } else { Console.WriteLine(" " + s2); } } } private static void test(string s) { Console.WriteLine(s); Console.WriteLine("replace and split: "); replaceandsplit(s); Console.WriteLine("split and replace: "); splitandreplace(s); Console.WriteLine("manual parse: "); manualparse(s); Console.WriteLine("regex parse: "); regexparse(s); } public static void Main(string[] args) { test("123,\"abc\",\"\"\"quoted\"\"\",\"partly \"\"quoted\"\" !\",\"a,b,c\""); } }