using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; public class Test { public static void Main() { var s = @"_if_111_else_222_if__if_333_else_444_endif__else_555_if_666_else_777_endif__endif__endif_"; var pat = @"(?x)(?= # Start of the overlapping match capturing lookahead (_if_ # Leading delimiter (?> # Start of atomic group (no backtracking into it) (?!_(?:end)?if_). # Any symbol not starting the delimiter sequence |(?_if_) # A leading delimiter added to stack o |(?<-o>_endif_) # Trailing delimiter added to stack o )* # Repeat the atomic group 0+ times (?(o)(?!)) # If the o stack is not empty, fail the match _endif_ # Trailing delimiter ) )"; var res = Regex.Matches(s, pat) .Cast() .Select(p => p.Groups[1].Value) .Where(n => n.Contains("_else_")) .ToList(); foreach (var v in res) Console.WriteLine(v); } }