Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java delimiter for * and / in string tokens [duplicate]

Tags:

java

string

regex

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

like image 828
adne Avatar asked Feb 02 '26 21:02

adne


2 Answers

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:

[ +*/-]+

Regular expression visualization

Debuggex Demo

like image 110
arshajii Avatar answered Feb 04 '26 09:02

arshajii


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("[ +\\-*/]+");
like image 24
Pshemo Avatar answered Feb 04 '26 11:02

Pshemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!