1

I am trying to write a method that would split up an inputted math expression into all the individual operators and numbers. For example, 1 + 1 would produce an array of { 1, +, 1 } and 2 - -2 would produce an array of { 2, -, -2 }. I sort of got this working after doing some research on StackOverflow (using this question: Splitting a simple maths expression with regex) and I wrote the following:

String[] t = tokens.split("(?<=[-+*/()])|(?=[-+*/()])");

This works great with the 1 + 1, but doing 2 - -2 produces { 2, -, -, 2 }, which is not what I want. I am kind of new to splitting and regexes, so this may be a basic question that I am simply failing to properly research, but any help would be greately appreciated! Also, I realize it would be super easy to just separate by spaces, but I'd really like to avoid that. Thanks a lot for any help!

Community
  • 1
  • 1
Thomas Paine
  • 303
  • 4
  • 13

2 Answers2

2

This works as you want.

String[] t = "2-2+-2".split("(?=[-+*/()])|(?<=[^-+*/][-+*/])|(?<=[()])");
// ==> {"2", "-", "2", "+", "-2"}
findall
  • 2,176
  • 2
  • 17
  • 21
0

By adding [0-9]+ to the beginning of your regex pattern, like so:

String[] t = tokens.split("[0-9]+(?<=[-+*/()])|(?=[-+*/()])");

you force the first matching expression to precede a series of numbers instead of preceding anything at all. The result is:

[2 , - , -2]

which is not perfect, but at least you have the right tokens now, after you trim the excess space.

gknicker
  • 5,509
  • 2
  • 25
  • 41
  • This works but now 2 - 2 results in { 2, -2 } instead of { 2, -, 2}. Is there a way that it can do both 2 - -2 and 2 - 2? – Thomas Paine Feb 04 '15 at 04:32