Issue
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
Solution
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)
Answered By - Abra
Answer Checked By - Cary Denson (JavaFixing Admin)