0

I have a conundrum, I need to separate a possible varied math string into separate entities to store in an ArrayList.

Input is read from a scanner could be any of the following.

Scanner input = new Scanner(System.in);
String read = input.nextLine();
ArrayList al = new ArrayList();

-5 + 10 //possible value of read
9--5   //possible value of read
-20* 10 //possible value of read

Basically I need to grab the first number and a potential negative sign, all ignoring leading or trailing whitespace and store it, then take the next character ignoring whitespace and store it (the operator of the problem), and then the next number with an optional negative sign, again ignoring whitespace.

I'm not very good with regex, and there's a lot of complicated possibilities here that I don't know how to tackle.

If I had to lay it out logically, I would say it thusly:

Get first non-whitespace character and end at last number digit that directly follows it.

Get next non-whitespace character

Get next non-whitespace character and end at last number digit that directly follows it.

Any pointers on syntax to accomplish that?

EDIT: I'm not simply trying to evualuate the result of the expression in question, I need to break it up and store it in an ArrayList to manipulate later as part of a Fraction Class.

user3066571
  • 1,381
  • 4
  • 14
  • 37

1 Answers1

0

Not really elegant, but if you are looking for the Regex to grab numbers both positive and negative, you can use this regex

-?\d+|\*|\/|\+|\-

- looks for negative numbers

? makes it an optional search

\d looks for a digit

+ grabs everything until a whitespace

the pipes mean "or" so it will grab a positive negative number, or an *, or an /, or a + or a -

Alex Mac
  • 63
  • 8