C#正则表达式如何判断字符串中包含的圆括号“(” 和“)”的个数

ljz_08 2013-05-25 10:50:25
我想判断字符串中"("和")"个数是否匹配,用下面的方法有问题:
string input = "abc(de)fg(hijkl)()";
int count1 = Regex.Matches(input, "(").Count;//运行报错:正在分析“(”- ) 不足
int count2 = Regex.Matches(input, ")").Count;//运行报错:正在分析“)”- ) 过多

如果加了转义字符:
string input = "abc(de)fg(hijkl)()";
int count1 = Regex.Matches(input, "\(").Count;//编译报错:无法识别的转移序列
int count2 = Regex.Matches(input, "\)").Count;//编译报错:无法识别的转移序列

这样也不行:
string input = "abc(de)fg(hijkl)()";
int count1 = Regex.Matches(input, @"(").Count;//运行报错:正在分析“(”- ) 不足
int count2 = Regex.Matches(input, @")").Count;//运行报错:正在分析“)”- ) 过多

如何才能达到我想要的目的呢
...全文
561 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ljz_08 2013-05-25
  • 打赏
  • 举报
回复
哈哈,还真是呢!
EnForGrass 2013-05-25
  • 打赏
  • 举报
回复
string input = "abc(de)fg(hijkl)()"; int count1 = Regex.Matches(input, @"\(").Count; int count2 = Regex.Matches(input, @"\)").Count; 这样不会报错啊
ljz_08 2013-05-25
  • 打赏
  • 举报
回复
嗯嗯,试了一下,也可以
游戏人间 2013-05-25
  • 打赏
  • 举报
回复
string input = "abc(de)fg(hijkl)()"; int count1 = Regex.Matches(input, "\\(").Count;//编译报错:无法识别的转移序列 int count2 = Regex.Matches(input, "\\)").Count;//编译报错:无法识别的转移序列 这样也可以的

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧