title: Count matching brackets in python string
body: <p>A user types a string containing regular expressions like this one:</p>
  
  <pre><code>'I have the string "(.*)"'
  </code></pre>
  
  <p>or</p>
  
  <pre><code>'when user enters (\d+) times text "(.*)" truncate spaces'
  </code></pre>
  
  <p>I need to count each matching brackets' occurrence as user types, so above texts would return count one for the first text and 2 for the second. On the other hand a bracket without a matching one shouldn't be counted:</p>
  
  <pre><code>'I am in the middle of writing this ('
  </code></pre>
  
  <p>Also I would like to avoid counting nested brackets.
  As this code will be executed in certain circumstances on <em>every</em> keystroke in vim (it's a part of a snippet for UltiSnips, so when I create the snippet and enter given placeholder this count function should evaluate what I type on each new char) it needs to be fast ;)</p>
  
  <p>To sum up requirements:</p>
  
  <ol>
  <li>Count bracket pairs</li>
  <li>Do not count bracket without a matching one</li>
  <li>Do not count nested brackets</li>
  <li>Count fast ;)</li>
  </ol>
  
  <p>As requested - here is my initial effort to make this work:
  <a href="https://gist.github.com/3142334" rel="nofollow">https://gist.github.com/3142334</a></p>
  
  <p>It works, but unfortunately it counts inner brackets too, so I need to tweak it more.</p>
  
  <p>Here is another solution that counts only outer brackets:</p>
  
  <pre><code>def fb(string, c=0):
      left_bracket = string.find("(")
      if left_bracket &gt; -1:
          string = string[left_bracket + 1:]
          right_bracket = string.find(")")
          if right_bracket &gt; -1:
              if string[:right_bracket].find("(") == -1:
                  c += 1
              string = string[right_bracket + 1:]
          return fb(string, c)
      else:
          return c
  </code></pre>