1

I have some expressions with AND, OR operators. + being AND, / being OR. I need to extract expressions within parentheses separated by operators.

Example:

Expression                    Output

(A + B)/(C + D)              (A + B),   (C + D)
(A / B)+(C / D)              (A / B),   (C / D)
(A + B / C)+(A / B)          (A + B / C),   (A / B)

Expressions can have any combination. All I need is to look at the logical operator & get data in the parentheses.

exp.split("((?<=&&)|(?=&&)|(?<=\\|\\|)|(?=\\|\\|)|(?<=\\()|(?=\\()|(?<=\\))|(?=\\)))");

But this splits on each character. I need regex to look for operators & split on that giving me data inside the parentheses as quoted in the example above.

 If i also want the operator along with data how could it be done?

Example : 
(A + B)/(C + D)   should give me (A + B), /, (C + D)
(A + B / C)+(A / B) should give me (A + B / C), +, (A / B)
SilentCoder
  • 47
  • 1
  • 10

2 Answers2

1

I don't think you can do this with split. You could use a regex Matcher and iterate over the groups:

String input = "(A + B / C)+(A / B)";

//capture a group for each expression contained by parentheses
Pattern pattern = Pattern.compile("(\\(.*?\\))");

//create a matcher to apply the pattern to your input
Matcher matcher = pattern.matcher(input);

//find every match and add them to a list
List<String> expressions = new ArrayList<>();
while(matcher.find()) {
    expressions.add(matcher.group());
}

System.out.println(expressions);

prints [(A + B / C), (A / B)]

Alex Wittig
  • 2,800
  • 1
  • 33
  • 42
  • Thanks. Works like a charm. A small update to the question. If my expression has a nested parenthesis like ((A + B))/C) + D then how should the Pattern change? – SilentCoder Jan 29 '14 at 21:09
  • @sarath in general, a single RegEx can't handle nested recursive structures. If that's what you have, you're quite likely to run into trouble. You'll probably have to do the recursion yourself. – Ian McLaird Jan 29 '14 at 21:11
  • @sarath What Ian said. See http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns – Alex Wittig Jan 29 '14 at 21:13
  • @IanMcLaird : Oh allright. I just asked because that could be sometimes of a case & I need to make sure i get the right output. – SilentCoder Jan 29 '14 at 21:14
  • @sarath: You can write regexes for the parts, use them in loop and count the depth yourself. For things like splitting into two top-level expressions it's trivial. Overall it's a very good idea as then you have to process the parts and so you need multiple passes. – maaartinus Jan 29 '14 at 21:50
0
 If i also want the operator along with data how could it be done?

    Example : 
    (A + B)/(C + D)   should give me (A + B), /, (C + D)
    (A + B / C)+(A / B) should give me (A + B / C), +, (A / B)

To do this, i hope this should work

exp.replaceAll("\\([^)]*?\\)", "")
SilentCoder
  • 47
  • 1
  • 10