我在这个问题上有一些困难.我需要删除波形括号中包含的所有数据.
像这样:
Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there.
变为:
Hello there.
这是我第一次尝试(我知道这很可怕):
while 1:
firstStartBracket = text.find('{{')
if (firstStartBracket == -1):
break;
firstEndBracket = text.find('}}')
if (firstEndBracket == -1):
break;
secondStartBracket = text.find('{{',firstStartBracket+2);
lastEndBracket = firstEndBracket;
if (secondStartBracket == -1 or secondStartBracket > firstEndBracket):
text = text[:firstStartBracket] + text[lastEndBracket+2:];
continue;
innerBrackets = 2;
position = secondStartBracket;
while innerBrackets:
print innerBrackets;
#everytime we find a next start bracket before the ending add 1 to inner brackets else remove 1
nextEndBracket = text.find('}}',position+2);
nextStartBracket = text.find('{{',position+2);
if (nextStartBracket != -1 and nextStartBracket < nextEndBracket):
innerBrackets += 1;
position = nextStartBracket;
# print text[position-2:position+4];
else:
innerBrackets -= 1;
position = nextEndBracket;
# print text[position-2:position+4];
# print nextStartBracket
# print lastEndBracket
lastEndBracket = nextEndBracket;
print 'pos',position;
text = text[:firstStartBracket] + text[lastEndBracket+2:];
它似乎工作,但内存不足很快.有没有更好的方式来做(希望与正则表达式)?
编辑:我不清楚,所以我再举一个例子.我需要允许多个顶级括号.
像这样:
Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there {{my }} friend.
变为:
Hello there friend.