这个问题我有点困难。我需要删除方括号中包含的所有数据。在
像这样:Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there.
变成:
^{pr2}$
这是我的第一次尝试(我知道这很糟糕):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:];
它似乎有用,但很快就用完了内存。有没有更好的方法来实现这一点(希望使用regex)?在
编辑:我不清楚,所以我再举一个例子。我需要考虑多个顶层括号。在
像这样:Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there {{my }} friend.
变成:Hello there friend.