替换位于其间的字符串

use*_*786 15 python regex string

这里是我的问题:在一个变量,文本和包含逗号,我尝试删除只设两个字符串(事实上之间的逗号[]).例如,使用以下字符串:

input =  "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
output = "The sun shines, that's fine [not for everyone] and if it rains, it Will Be better."
Run Code Online (Sandbox Code Playgroud)

我知道如何使用.replace整个变量,但我不能为它的一部分做.这个网站上有一些主题正在接近,但我没有设法利用它们来解决我自己的问题,例如:

Igo*_*bin 20

import re
Variable = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
Variable1 = re.sub("\[[^]]*\]", lambda x:x.group(0).replace(',',''), Variable)
Run Code Online (Sandbox Code Playgroud)

首先,你需要找到需要重写的字符串部分(你这样做re.sub).然后你重写那些部分.

该函数var1 = re.sub("re", fun, var)意味着:找到var符合的变量中的所有子串"re"; 用功能处理它们fun; 返回结果; 结果将保存到var1变量中.

正则表达式"[[^]]*]"表示:查找以[(\[在re中)开头的子字符串,包含除]([^]]*在re中)和以](\]在re中)结束的所有内容.

对于每个找到的事件,运行一个将此事件转换为新事件的函数.功能是:

lambda x: group(0).replace(',', '')
Run Code Online (Sandbox Code Playgroud)

这意味着:获取找到的字符串(group(0)),替换','''(删除,换句话说)并返回结果.