fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6.  
  7. public class Test
  8. {
  9. public static void Main()
  10. {
  11. var s = @"_if_111_else_222_if__if_333_else_444_endif__else_555_if_666_else_777_endif__endif__endif_";
  12. var pat = @"(?x)(?= # Start of the overlapping match capturing lookahead
  13. (_if_ # Leading delimiter
  14. (?> # Start of atomic group (no backtracking into it)
  15. (?!_(?:end)?if_). # Any symbol not starting the delimiter sequence
  16. |(?<o>_if_) # A leading delimiter added to stack o
  17. |(?<-o>_endif_) # Trailing delimiter added to stack o
  18. )* # Repeat the atomic group 0+ times
  19. (?(o)(?!)) # If the o stack is not empty, fail the match
  20. _endif_ # Trailing delimiter
  21. )
  22. )";
  23. var res = Regex.Matches(s, pat)
  24. .Cast<Match>()
  25. .Select(p => p.Groups[1].Value)
  26. .Where(n => n.Contains("_else_"))
  27. .ToList();
  28. foreach (var v in res)
  29. Console.WriteLine(v);
  30. }
  31. }
Success #stdin #stdout 0.13s 24768KB
stdin
Standard input is empty
stdout
_if_111_else_222_if__if_333_else_444_endif__else_555_if_666_else_777_endif__endif__endif_
_if__if_333_else_444_endif__else_555_if_666_else_777_endif__endif_
_if_333_else_444_endif_
_if_666_else_777_endif_