利用正则表达式(Regular Expression)检查/统计括号对

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并不提倡使用异常来处理问题的,所以使用这个方法会有点牵强!

所以本人要表达的是:当不能直接(或者说难以)去解决问题的话,就要考虑下有其它办法了(当然这里检查括号是否配对也可以用几个循环来写).其中①②会体现出来.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值