using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; public class Test { public static void Main() { var text = "ISNULL(d.Type, 0), d.Subject + ', ' + d.Name, d.Something,array_position(ARRAY['f', 'p', 'i', 'a']::varchar[], x_field), test"; var pattern = @"(\([^()]*\)|'[^']*')|\s*,"; var result = Regex.Replace(text, pattern, m => m.Groups[1].Success ? m.Value : " DESC,"); Console.WriteLine(result); } }