Home > Software engineering >  Extract string enclosed by parenthesis
Extract string enclosed by parenthesis

Time:09-27

I have the following string

“test IF(one,2,2) Wow IF(two,1,1)”

I need to get the following strings:

IF(one,2,2)
IF(two,1,1)

I tried the following regex but it only gives me the following with missing close parenthesis

Pattern pattern.compile(“IF(([^)] ))”);
Matcher matcher = pattern.match(formula);
While(matcehr.find()) {
    System.out.println(matcher.group(0));
}

Result is

IF(one,2,2

CodePudding user response:

The below code achieves your desired result:

public class MyClass {
    public static void main(String args[]) {
        String formula = "test IF(one,2,2) Wow IF(two,1,1)";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("IF\\(.*?\\)");
        java.util.regex.Matcher matcher = pattern.matcher(formula);
        while(matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }
}

The regular expression is the literal string IF followed by a (literal) opening parenthesis (i.e. () followed by zero or more characters. The question mark is a reluctant qualifier which means that the string of any characters will be terminated by the first closing parenthesis encountered. Refer to this regex101 and this JDoodle as well as the documentation for class java.util.regex.Pattern.

Running the above code produces the following output:

IF(one,2,2)
IF(two,1,1)

CodePudding user response:

You should escape the parenthesis.

IF(\([^)] \))

With this, it should work. You will find a list of characters that need to be escaped (though there it is for javasript) in a regex here: List of all characters that should be escaped before put in to RegEx? In summary, generally, you should escape these characters: . \ * ? [ ^ ] $ ( ) { } = ! < > | : -

  • Related