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.

5
  • 7
    Why not use an actual parser? Commented Jan 7, 2013 at 23:43
  • 1
    I agree, there are libraries and such made for this Commented Jan 7, 2013 at 23:44
  • You're on the right track , so keep that up . Although if you need a quick-fix , parsers!! Commented Jan 7, 2013 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. Commented Jan 7, 2013 at 23:54
  • If you want to parse mathematical expressions like this, the right way to do it is with the shunting yard algorithm. It's surprisingly difficult to do with ordinary kinds of parsers. Commented Jan 8, 2013 at 0:00

3 Answers 3

2

Try this:

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.