2015-04-04 80 views
1

我想使用正则表达式来摆脱特定字符之间的字符串,例如“[”和“]”:删除文本

input = "There is a [blue] cloud on top of that [big] elephant"; 
desiredOut = "There is a cloud on top of that elephant"; // this is what i want 

但是,如果使用正则表达式更换什么是“[”和“]”我删除了第一个和最后这个人物之间的一切之间:

string input = "There is a [blue] cloud on top of that [big] elephant"; 
string regex = "(\\[.*\\])" ; 
string actualOut = Regex.Replace(input, regex, ""); 

actualOut = "There is a elephant" // this is what i get 

如何卸下inmediate分隔符之间的东西任何线索?谢谢。

回答

1

这一细小的改动应该解决您的问题:

string regex = "\\[(.*?)\\]"; 

该位(.*?)会匹配一切,但将采取尽可能少。

+0

谢谢你!那就是诀窍。 – Santi 2015-04-05 12:29:29

0
var input = "There is a (blue) cloud on top of that(big) elephant"; 
var output = Regex.Replace(input, @" ?\(.*?\)", string.Empty); 

这将做的工作

+0

请添加一些解释。 – 2015-04-04 18:50:13

0

您的正则表达式删除第一个[和最后]之间的所有内容的原因是因为默认情况下修饰符是贪婪的,即。它们匹配尽可能多的字母。

您可以使用懒人比赛在其他的答案,或者您可以使用

string regex = @"\[[^\]]*\]" 

此正则表达式左方括号匹配,那么它需要什么除了右括号,然后结束在右方括号中。

0

还去除前导或尾随的空间,你可以使用这个

string actualOut = Regex.Replace(input, @"^\[[^\]]*\]\s+|\s+\[[^\]]*\]", ""); 

DEMO