I'm having some difficulty with this problem. I need to remove all data that's contained in squiggly brackets.
Like such:
Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there.
Becomes:
Hello there.
Here's my first try (I know it's terrible):
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:];
It seems to work but runs out of memory quite fast. Is there any better way to do this (hopefully with regex)?
EDIT: I was not clear so I'll give another example. I need to allow for multiple top level brackets.
Like such:
Hello {{world of the {{ crazy}} {{need {{ be}}}} sea }} there {{my }} friend.
Becomes:
Hello there friend.