1

I asked a similar question recently, but I need some more help.

The user will be able to enter a string, for example:

"-5-1/-2"

It needs to: delimit by +,-,*,/,(,) and negative numbers should be kept together, in this case -5 and -2 should stay together.

This is what I currently have:

String userStrWithoutSpaces=userStr.replaceAll(" ", "");
String[] tokens = userStrWithoutSpaces.split("(?<=[\\-+*/=()])|(?=[()\\-+*/=])");

Which works besides keeping negative numbers together.

Thanks in advance.

A--C
  • 36,351
  • 10
  • 106
  • 92
Wrath
  • 825
  • 1
  • 6
  • 6
  • 7
    Why not use an actual parser? – Mechanical snail Jan 07 '13 at 23:43
  • 1
    I agree, there are libraries and such made for this – jackcogdill Jan 07 '13 at 23:44
  • You're on the right track , so keep that up . Although if you need a quick-fix , parsers!! – Caffeinated Jan 07 '13 at 23:48
  • Be aware that most parsers (I believe) for arithmetic expressions consider that minus as a unary operator, rather than as part of the number; normally, it makes things more consistent and easy. – leonbloy Jan 07 '13 at 23:54
  • If you want to parse mathematical expressions like this, the right way to do it is with the [shunting yard algorithm](http://en.wikipedia.org/wiki/Shunting-yard_algorithm). It's surprisingly difficult to do with ordinary kinds of parsers. – Tom Anderson Jan 08 '13 at 00:00

3 Answers3

2

Try this:

String[] tokens = userStrWithoutSpaces.split(
    "(?<=[+*/=()])|((?<=-)(?!\\d))|(?=[()\\-+*/=])");

This uses a lookahead to not split when hyphen is followed by digit

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

I would use JFlex. You need a lexical analyzer, a piece of code, which will give you tokens from some input text. JFlex is a generator of lexical analyzers. Very fast and reliable analyzers. You specify only a rules, in a form similiar to regular expressions, very convenient. All the low-level job does JFlex. The picture presents idea of JFlex:

enter image description here

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
0

Get the result of the arithmetic expression in Java:

How to parse a mathematical expression given as a string and return a number?

Parse it into its number and operator components in java:

Splitting a simple maths expression with regex

Community
  • 1
  • 1
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335