Peary Peary - 1 year ago 69
Java Question

String Split Situation

I have a fairly specific problem, where I want to take an equation and break it up, but also pay attention to negative numbers. Like:

exampleString = "12--5*-2"

Using that string I wish to split it into 3 number values:

[12, -5, -2]

Ive got it to work with double subtraction by splitting

That will give me
[6, 8, -5]

But I don't know how to modify it to work with all the operators, for example:

[5, -2]

I feel like this should be able to work and I've spent a few hours searching but haven't come across anything that will do it. Any help or suggestions would be appreciated, cheers.

Answer Source

You could use a regular expression like the following to split the string.


The regular expression will split at any of the specified chars *,/,+,- iff the previous char was not a match (-> '--' will split only at the first '-').

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download