Reputation: 47
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)
Upvotes: 1
Views: 1183
Reputation: 47
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("\\([^)]*?\\)", "")
Upvotes: 0
Reputation: 2900
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)]
Upvotes: 1