fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6.  
  7. namespace SO13389560Balancing
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. string s = "~(a b (c) d (e f (g) h) i) j (k (l (m) n) p) q";
  14. string pattern = @"
  15. (?<=
  16. (?(Depth)(?!)) # 4. Finally, make sure there are no extra closed parentheses.
  17. ~\(
  18. (?> # (non backtracking)
  19. [^()] # 3. Allow any other character
  20. |
  21. \( (?<-Depth>)? # 2. When seeing an open paren, decreace depth if possible.
  22. # Also allow excess parentheses: '~((((((a' is OK.
  23. |
  24. (?<Depth> \) ) # 1. When seeing a closed paren, add to depth.
  25. )*
  26. )
  27. \w # Match your letter";
  28.  
  29.  
  30. s = Regex.Replace(s, pattern, "!", RegexOptions.IgnorePatternWhitespace);
  31.  
  32. Console.WriteLine(s);
  33. //Console.ReadKey();
  34. }
  35. }
  36. }
  37.  
Success #stdin #stdout 0.07s 38280KB
stdin
Standard input is empty
stdout
~(! ! (!) ! (! ! (!) !) !) ! (! (! (!) !) !) !