I have a string:
String str = \"a + b - c * d / e < f > g >= h <= i == j\";
I want to split the string on all of the operators
You could split on a word boundary with \b
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];
This should do it. Everything nicely stored in res
.
str.split (" ")
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)
String str = "a + b - c * d / e < f > g >= h <= i == j";
String reg = "\\s*[a-zA-Z]+";
String[] res = str.split(reg);
for (String out : res) {
if (!"".equals(out)) {
System.out.print(out);
}
}
Output : + - * / < > >= <= ==
Can you invert your regex so split by the non operation characters?
String ops[] = string.split("[a-z]")
// ops == [+, -, *, /, <, >, >=, <=, == ]
This obviously doesn't return the variables in the array. Maybe you can interleave two splits (one by the operators, one by the variables)
You could also do something like:
String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");
It handles white spaces and words of variable length and produces the array:
[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]