using System; using System.Linq; using System.Text.RegularExpressions; namespace ConsoleApplication1 { public class Program { public static void Main(string[] args) { var implicitParenRegexes = @" (a)(?(?=.) )(b) (c) (a)(?(?!z) )(b) (c) (a)(?(?<=.) )(b) (c) (a)(?(?.) )(b) (c) (a)(?(?(1).) )(b) (c) ((?a))(?(?(n).) )(b)(c) (a)(?(?(?:.).) )(b) (c) (a)(?(?.) )(b) (c) (a)(?(?'n'.) )(b) (c) (a)(?(?'-n' .) )(b) (c) (?a)(?(?.) )(b) (c) (a)(?(?# comment) )(b) (c) (a)(?(?i) )(b) (c) (a)(?(?(.).) )(b) (c) ".Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); var explicitParenRegexes = @" (a)(?((?=.)) )(b) (c) (a)(?((?!z)) )(b) (c) (a)(?((?<=.)) )(b) (c) (a)(?((?.)) )(b) (c) (a)(?((?(1).)) )(b) (c) ((?a))(?((?(n).)) )(b)(c) (a)(?((?(?:.).)) )(b) (c) (a)(?((?.)) )(b) (c) (a)(?((?'n'.)) )(b) (c) (a)(?((?'-n' .)) )(b) (c) (?a)(?((?.)) )(b) (c) (a)(?((?# comment)) )(b) (c) (a)(?((?i)) )(b) (c) (a)(?((?(.).)) )(b) (c) ".Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); Console.WriteLine("IMPLICIT PARENTHESIZED CONDITIONS:"); foreach (var pattern in implicitParenRegexes) CheckPattern(pattern); Console.WriteLine("\nEXPLICIT PARENTHESIZED CONDITIONS:"); foreach (var pattern in explicitParenRegexes) CheckPattern(pattern); Console.ReadKey(); } const string input = "a b c"; static void CheckPattern(string pattern) { Console.Write("Regex: '{0}'; groups: ", pattern); // Comment this block to get the exception if (pattern.Contains("(?(?i)")) { Console.WriteLine("Skipped to allow it run in ideone"); return; } try { int index = 1; Console.WriteLine(string.Join("; ", Regex.Match(input, pattern).Groups.Cast().Skip(1).Take(3) .Select(g => string.Format("${0}: '{1}'", index++, g.Value)))); } catch (Exception exception) { Console.WriteLine("ERROR: {0}: {1}", exception.GetType().Name, exception.Message); } } } }