Java replaceAll(..)和正则表达式

时间:2017-03-10 08:22:06

标签: java regex string replaceall

如何删除带括号的文字?

String string = "product(version(id),code),user(uid)";
string = string.replaceAll("\\(.*\\)", "");
System.out.println("string= " + string);

当我这样做时,我得到:

string= product

但我想得到

string= product,user

祝你好运!

1 个答案:

答案 0 :(得分:1)

试试这个:

String string = "(product(version(id),code),use)r(uid)";
StringBuilder sb = new StringBuilder();
    int countOpenPar = 0;
    for (int i=0; i<string.length(); i++) {
      char c = string.charAt(i);

      if( c == '(' ){
        countOpenPar++;
      }else if( c == ')' ){
        countOpenPar-- ;
      }else if( countOpenPar == 0){
        sb.append(c);
      }
    }
    System.out.println("string= " + sb.toString());