python双中括号_在python中使用嵌套子括号删除双重矩形括号之间的数据

我在这个问题上有一些困难.我需要删除波形括号中包含的所有数据.

像这样:

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值