I was wondering if it was possible to split a string on whitespace, and avoid all numbers, whitespace and operators such as + and -
This is what I have, but I believe it is incorrect
String [] temp = expression.split("[ \\+ -][0-9] ");
Suppose I have an expression
x+y+3+5+z
I want to get rid of everything else and only put x, y, and z into the array
I think you mean this:
String[] temp = expression.split("[\\s0-9+-]+");
This splits on whitespace, 0 to 9, +
and -
. Note that the characters appear in a single character class, not multiple separate character classes. Also the -
doesn't need escaping here because it is at the end of the character class.
I think this is what you're after:
String[] tmp = expression.split("[^a-zA-Z]+");
which should treat the separator as being anything that isn't a sequence of letters.
Test Run
public class foo {
static public void main(String[] args) {
String[] res = args[0].split("[^a-zA-Z]+");
for (String r: res) {
System.out.println(r);
}
}
}
% javac foo.java
% java foo x+y+3+5+z
x
y
z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With