Wrath
Wrath

Reputation: 875

How can I split a string for mathematical use in Java?

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.

Upvotes: 1

Views: 1084

Answers (3)

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

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

Upvotes: 1

Bohemian
Bohemian

Reputation: 424983

Try this:

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

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

Upvotes: 2

Eric Leschinski
Eric Leschinski

Reputation: 153822

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

Upvotes: 0

Related Questions