这是一个基于堆栈的解决方案。当输入是某个控制字符时,仅计算整个字符串中的大括号会更快,但由于在键入之前进行文本选择和其他原因,这很棘手。这也不是非常pythonic,但它似乎工作,它相对较快:
#!/usr/bin/env python
import re
def bracecounter(s):
count = 0; open = 0; braces = []
for c in s:
if c in '()':
braces.append(c)
if c == '(':
open += 1
else:
if ''.join(braces[-2:]) == '()':
braces = braces[:-2]
if open == 1:
count += 1
open -= 1
else:
pass # closing brace without matching opening brace
return count
fix = [
(1, 'I have the string "(.*)"'),
(2, 'when user enters (\d+) times text "(.*)" truncate spaces'),
(0, 'I am in the middle of writing this ('),
(1, ') Nested ((braces) will (not) count))))))).'),
]
def test():
for exp, s in fix:
res = bracecounter(s)
assert exp == res, "Brace count %s != %s for '%s'" % (res, exp, s)
if __name__ == '__main__':
test()