1.去除括弧内的字符
using System.Text.RegularExpressions; var majorname = "ATM0243(Dispaly)".Replace("(", "(").Replace(")",")"); majorname = Regex.Replace(majorname.Replace("(", "(").Replace(")", ")"), @"\([^\(]*\)", ""); 最终得到结果:ATM0243
2.截取括号里的字符串
str = System.Text.RegularExpressions.Regex.Replace(@"带括号的(ddd)字符串", @"(.*\()(.*)(\).*)", "$2");//
3.如何去掉字符串首尾特定字符(串)?
/// /// 截前后字符(串) /// ///原字符串 ///要截掉的字符串 ///是否贪婪 /// private string GetString(string val,string str,bool all) { return Regex.Replace(val, @"(^(" + str + ")" + (all ? "*" : "") + "|(" + str + ")"+(all ? "*" : "") + "$)", ""); }
4.利用正则表达式取出括号中的内容,多个括号
string source = "(abc)de(fg)hi(jk)"; Regex reg = new Regex(@"(?is)(?<=\()[^\)]+(?=\))"); MatchCollection mc = reg.Matches(source); foreach (Match m in mc) { MessageBox.Show(m.Value); }