Mayur Jadhav
Mayur Jadhav

Reputation: 96

Java String.split() Regex to split mathematical expression

I have a string:

"a + b - (2.5 * d / 2) < f > g >= h <= (i == j)"

Currently I've :

String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];

But this doesn't handle brackets. And also it separates out operators and values, but I want single regex which will split above expression like this:

[a, +, b, -, (, 2.5, *, d, /, 2, ), <, f, >, g, >=, h, <=, (, i, ==, j, )]

Upvotes: 2

Views: 1299

Answers (1)

Adam
Adam

Reputation: 36703

I think this might be easier to express as the tokens you're trying to extract rather than a split regex.

String input = "-9 + a + b - (2.5 * d / 2) < f > g >= h <= (i == j) && (foo || bar)";
Pattern pattern = Pattern.compile("-?[0-9.]+|[A-Za-z]+|[-+*/()]|==|<=|>=|&&|[|]{2}");
Matcher match = pattern.matcher(input);
List<String> actual = new ArrayList<String>();
while (match.find()) {
    actual.add(match.group());
}
System.out.println(actual);

This gives you the result you're after

[-9, +, a, +, b, -, (, 2.5, *, d, /, 2, ), f, g, >=, h, <=, (, i, ==, j, ), &&, (, foo, ||, bar, )]

Upvotes: 4

Related Questions