This question already has answers here:
Regexp to remove nested parenthesis
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
如何删除带括号的文本?

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


当我这样做时,我得到:

string= product


但我想得到

string= product,user


最好的祝福!

最佳答案

尝试这个:

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());

关于java - Java replaceAll(..)和正则表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42713555/

10-13 09:53