0

I need to create a REGEX that will capture the last expression of the 'if' clause.

For example, given the following statement:

  if ( if( (1+1 == 2, 1, 2)), 3);

I want to match:

((1+1 == 2, 1, 2))

I tried this, but it does not work:

if\(\.*^(?!if)\)
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
H H
  • 9
  • 1

2 Answers2

4

You can use the following regex:

if\(\s*\([^()]*\)\)

RegEx Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String args[]) {
        Matcher matcher = Pattern.compile("if\\(\\s*\\([^()]*\\)\\)").matcher("if ( if( (1+1 == 2, 1, 2)), 3);");
        if (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

Output:

if( (1+1 == 2, 1, 2))

Explanation of the regex from regex101:

enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

This regexp runs , the result is in in group 1 ( $1 )

^if\s?((.),.);$

hgregoire
  • 111
  • 1
  • 3