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