0

I am trying to write a regex for delimiters “(“, “)”, “,”. I tried to write a regex but it is not the correct for the delimeters.

Let's say the input is mult(3,add(2,subs(4,3))). The output with my delimeter regex is: 3,add(2,subs(4,3.

public class Practice {

    private static final String DELIMETER = "\\((.*?)\\)";

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        String arg = reader.next();
        Pattern p = Pattern.compile(DELIMETER);
        Matcher m = p.matcher(arg);
        while (m.find()) {
            System.out.println(m.group(1));
        }
    }
}

What is the correct regex to get string between the delimeters?

Diana J
  • 43
  • 9

1 Answers1

0

In general, you cannot use a regex to match anything which can nest recursively. However, if you removed the ? from your regex, it would match from the first ( to the last ), which might be good enough, depending on what you expect the input to look like.

mhsmith
  • 6,675
  • 3
  • 41
  • 58