Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "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.

like image 289
Peary Avatar asked Apr 20 '26 09:04

Peary


1 Answers

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 '-').

like image 144
Nevay Avatar answered Apr 21 '26 23:04

Nevay



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!