A user types a string containing regular expressions like this one:
'I have the string "(.*)"'
or
'when user enters (\d+) times text "(.*)" truncate spaces'
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:
'I am in the middle of writing this ('
Also I would like to avoid counting nested brackets. As this code will be executed in certain circumstances on every 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 ;)
To sum up requirements:
- Count bracket pairs
- Do not count bracket without a matching one
- Do not count nested brackets
- Count fast ;)
As requested - here is my initial effort to make this work: https://gist.github.com/3142334
It works, but unfortunately it counts inner brackets too, so I need to tweak it more.
Here is another solution that counts only outer brackets:
def fb(string, c=0):
left_bracket = string.find("(")
if left_bracket > -1:
string = string[left_bracket + 1:]
right_bracket = string.find(")")
if right_bracket > -1:
if string[:right_bracket].find("(") == -1:
c += 1
string = string[right_bracket + 1:]
return fb(string, c)
else:
return c