Reputation: 33
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 "6-8--5"
by "(?<!-)-"
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"
---> [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.
Upvotes: 3
Views: 49
Reputation: 794
You could use a regular expression like the following to split the string.
"(?<!\\G)[*/+-])"
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 '-').
Upvotes: 2