Search code examples
javaregexstringreplaceall

Java replaceAll(..) and Regular Expressions


How can I delete a text with parentheses?

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

When I do this, I get:

string= product

But I would like get

string= product,user

Best regards!


Solution

  • Try this:

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