I have a string like 22 + 4 * 3 / 4
Now, I need to extract the tokens from this string. Here is my one line code:
String[] tokens = str.split( [ +-*/]+ )
basically my delimiter string is [+-*/] As I want to split on the symbols + - * /
but then, unfortunately, this conflicts with regex version of *, / I tried adding backslash to * and / as [+-\*\/] but it doesnt help.
How do I make Java compile *, / by their literal meaning? I thought I had done as per the java documentation on patterns http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum
what did I miss here?
thanks
Actually, when used in a character class, * and + lose their special meaning (after all they would make no sense in a character class). Therefore, we don't need to escape these characters. Conversely, - only has a special meaning in a character class, but only if it used between characters, where it indicates a range. If it is used at the start or end, it has no special meaning. So, we have:
[ +*/-]+

Debuggex Demo
In character class [...] - is special character used to create range of characters like a-z. To make it literal you need to place it at start of class character [-...], end of class character [...-] or just simply escape it with \ which in Java needs to be written as "\\-". Try this way
String[] tokens = str.split("[ +\\-*/]+");
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