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

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

我想判断字符串中"("和")"个数是否匹配,用下面的方法有问题:
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;//运行报错:正在分析“)”- ) 过多
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;//编译报错:无法识别的转移序列

这样也可以的

Copyright © 2007-2012 www.chuibin.com 六维论文网 版权所有