import java.util.regex.*;
public class CountParentheses {
public static void main(String[] args) {
String source="abc}(kdj35{ki89898{(kki)kjdfkkf{{[[kkdf88]05]e=-}99}1`~}kk}..,)";//无意中输入多了第一个'}'
String target=source;
char[] charSource1={'{','['};// ① 假定源串中
char[] charSource2={'}',']'};//有这样的乱括号.
for (int i=0;i<charSource1.length ;i++ ) {//转换可能出现的不合字符,下同
target=target.replaceAll("//"+charSource1[i],"(");
}
for (int i=0;i<charSource2.length ;i++ ) {
target=target.replaceAll("//"+charSource2[i],")");
}
System.out.println("The source string: "+source+"/n"+"The converted string: "+target+
"/n*****now the soure string is proper bracket matched?*****/n");
Pattern m=null;
try {
//冒昧:利用异常获取错误提示!(如果不是为了统计括号对,
//则可以直接用String.replaceAll()产生以避免导入包.
m=Pattern.compile(target);// ②
}
catch (PatternSyntaxException e) {
String[] err=e.getMessage().split("/n");
System.out.println("Sad!!/n"+"the converted string: "+target+"/n"+err[0]+
"/n/nplease check the char with the index corresponding soure string!");
System.exit(1);
}
System.out.println("Ok!");//无异常则括号配对.
int i=m.matcher(target).groupCount();
System.out.println("*****共有 "+i+" 个配对括号!*****");
}
};
需要说明的是java并不提倡使用异常来处理问题的,所以使用这个方法会有点牵强!
所以本人要表达的是:当不能直接(或者说难以)去解决问题的话,就要考虑下有其它办法了(当然这里检查括号是否配对也可以用几个循环来写).其中①②会体现出来.