我需要在C#中从字符串中移除括号,具体请参见code-behind。
例如,如果我的字符串是[My [] Groups]
,我想将其变成My [] Groups
。
我需要在C#中从字符串中移除括号,具体请参见code-behind。
例如,如果我的字符串是[My [] Groups]
,我想将其变成My [] Groups
。
试试这个:
yourString = yourString.Replace("[", string.Empty).Replace("]", string.Empty);
string s = "[My [] Groups]";
string pattern = @"^(\[){1}(.*?)(\]){1}$";
Console.WriteLine(Regex.Replace(s, pattern, "$2")); // will print My [] Groups
使用您提供的字符串,最简单的解决办法是使用子字符串:
if (s.Length > 2) {
s = s.Substring(1, s.Length-2);
}
只有当您确信字符串的第一个和最后一个字符确实是方括号时,此方法才有效。如果它们不是方括号,例如未经修剪的字符串,则可能需要执行其他字符串操作(例如修剪字符串)。
使用简单的Trim
:
var result = "[My [] Groups]".Trim('[', ']');
请查看String.Replace
方法。
http://msdn.microsoft.com/en-us/library/fk49wtc1.asp
更新:
如果只是要删除封闭括号,那么可以直接去掉第一个和最后一个字符。可以使用dasblinkenlight提供的代码或正则表达式实现。
但一定要确定它们确实是括号。
如果使用正则表达式,你可以一次性完成所有操作。否则,你应该将类似于dasblinkenlight解决方案的内容添加到其中。
if (s.Length > 2) {
if(s.StartsWith("[")) {
s = s.Substring(1, s.Length-1);
}
if(s.EndsWith("]")) {
s = s.Substring(0, s.Length-1);
}
}
如果你只想在有起始和结束括号的情况下进行去除操作
if (s.Length > 2) {
if(s.StartsWith("[") && s.EndsWith("]")) {
s = s.Substring(1, s.Length-2);
}
}
检查长度是否大于2的部分可能可以去掉,但是我保留它是为了展示初始代码来源于dasblinkenlight编写的。
Regex.Replace("This [is [a] [test.", @"[\[\]]", "") // -> "This is a test."
string result = "[My [] Groups]".TrimLeft('[').TrimRight(']');
var myString = "[My Groups]";
myString.Replace("[", string.Empty);
myString.Replace("]", string.Empty);