python参数有中括号_在python中删除带有嵌套子方括号的双方括号之间的数据

这个问题我有点困难。我需要删除方括号中包含的所有数据。在

像这样: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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值