using System; using System.Collections.Generic; using System.Text.RegularExpressions; public class Test { public static void Main() { string hieroglyphics = @"^(?=^[^()]*(?>[^()]+|\((?)|\)(?<-DEPTH>))*(?(DEPTH)(?!))[^()]*$)[(]*[0-9a-zA-Z]+[)]*(\s+(&&|\|\|)\s+[(]*[0-9a-zA-Z]+[)]*)*$"; var tests = new List { // Working "(1 && 2)", "((1 && 2) && (3 || 4))", // Not working "1 && 2", "(1 && 2) && (3 || 4)", "Stack && Overflow" }; foreach (var test in tests) Console.WriteLine(test + ": " + Regex.IsMatch(test, hieroglyphics)); } }