我有一个字符串,如
'(((a+b)+a)+c)'
我想分成两部分,结果将是('((a+b)+a)','c')
。
如果我在结果的第一个元素上再次运行它会给我('(a+b)', 'a')
如果我在'(a+b)'
再次运行它,它将返回('a', 'b')
。
我以为我可以通过正则表达式做到这一点,但我无法弄明白这一点,并且走了许多if语句检查开始和结束括号的路径,但它有点乱“
答案 0 :(得分:1)
#!/usr/bin/python3.5
def f(s):
p=s.rsplit('+',1)
return [p[0][1:],p[1][:-1]]
s='(((a+b)+a)+c)'
for i in range(3):
k=f(s)
s=k[0]
print(k)
输出:
['((a+b)+a)', 'c']
['(a+b)', 'a']
['a', 'b']
答案 1 :(得分:1)
以下示例适用于您的示例:
def breakit(s):
count = 0
for i, c in enumerate(s):
if count == 1 and c in '+-':
return s[1:i].strip(), s[i+1:-1].strip()
if c == '(': count +=1
if c == ')': count -= 1
return s
breakit(s)
>> ('((a+b)+a)', 'c')
breakit(_[0])
('(a+b)', 'a')
breakit(_[0])
('a', 'b')
答案 2 :(得分:0)
我以为我也会发布我的答案,不如所选择的解决方案那么优雅,但它有效
def break_into_2(s):
if len(s) == 1:
# limiting case
return s
# s[0] can either be a digit or '('
if s[0].isdigit():
# digit could be 10,100,1000,...
idx = 0
while s[idx].isdigit():
idx += 1
a = s[:idx]
b = s[idx+1:]
return a, b
# otherwise, s[0] = '('
idx = 1
counter = 1
# counter tracks opening and closing parenthesis
# when counter = 0, the left side expression has
# been found, return the idx at which this happens
while counter:
if s[idx] == '(':
counter+=1
elif s[idx] == ')':
counter -=1
idx +=1
if s[:idx] == s:
# this case occurs when brackets enclosing entire expression, s
# runs the function again with the same expression from idxs 1:-1
return break_into_2(s[1:-1])
return s[:idx], s[idx+1:]