Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove parenthesis from String using java regex

Tags:

java

regex

I want to remove parenthesis using Java regular expression but I faced to error No group 1 please see my code and help me.

public String find_parenthesis(String Expr){
        String s;
        String ss;
        Pattern p = Pattern.compile("\\(.+?\\)");
        Matcher m = p.matcher(Expr);
        if(m.find()){
            s = m.group(1);
            ss = "("+s+")";
            Expr = Expr.replaceAll(ss, s);
            return find_parenthesis(Expr);
        }
        else
            return Expr;
    }

and it is my main:

public static void main(String args[]){
    Calculator c1 = new Calculator();
    String s = "(4+5)+6";
    System.out.println(s);
    s = c1.find_parenthesis(s);
    System.out.println(s);
}
like image 755
Ehsan Avatar asked Mar 31 '13 06:03

Ehsan


People also ask

How do you remove parentheses from a string?

To remove parentheses from string using Python, the easiest way is to use the Python sub() function from the re module. If your parentheses are on the beginning and end of your string, you can also use the strip() function.

What is $1 regex Java?

$0 = the entire matched substring (corresponding to matcher. group()), $1 = the first parenthesized match subpattern (corresponding to matcher.

How do I remove the starting and ending character from a string in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.


2 Answers

The simplest method is to just remove all parentheses from the string, regardless of whether they are balanced or not.

String replaced = "(4+5)+6".replaceAll("[()]", "");

Correctly handling the balancing requires parsing (or truly ugly REs that only match to a limited depth, or “cleverness” with repeated regular expression substitutions). For most cases, such complexity is overkill; the simplest thing that could possibly work is good enough.

like image 129
Donal Fellows Avatar answered Sep 18 '22 15:09

Donal Fellows


What you want is this: s = s.replaceAll("[()]","");

For more on regex, visit regex tutorial.

like image 45
Justin Avatar answered Sep 18 '22 15:09

Justin