Two regular expression problems/questions

Hi!

I wonder if you kind people kan help me with a couple of problems regarding regular expressions in Java.

1. I want to use a regEx to split a string into an array like the following:

**Input:** 1+2/3 **Array:** {1,+,2,/,3}

The problem, however, is that when I give an input of a number greater than 9 it does like this:

**Input:** 12+3 **Array:** {1, 2, +, 3} (I hoped to get "12, +, 3"...)

How can I make a ragEx that looks for ALL digits up to the operator?

2. When I split the string I also want it to split (-1) into the array like the following:

**Input:** (-3)+2 **Array:** {(-3), +, 2}

Though when it gets this input it skips it completely...

The regular expression I use for the splitting is the following:

*\\(-\\d*\\)|\\d*|\\(-\\d*[,|.]\\d*\\)|\\d*[,|.]\\d*|[+|\\-|*|/|^]*

It checks for things in the following order: **(-number)** or **number** or **(-numberWithDecimal)** or **numberWithDecimal** or **operator**.

Since I got no delimiters in the input I can't simply use String's split() method.

Thanks in advance / Komposten

Re: Two regular expression problems/questions

I once wrote a blog article on expression parsing; maybe you like to read it (there's a "blog" button near the top of this page). The article also contains source code that works.

kind regards,

Jos

Re: Two regular expression problems/questions

May this be the post you are referring to?

**Compilers**

Re: Two regular expression problems/questions

Well, I think I've found the post you were referring to.

However I'm not doing this in with the goal of best design, I'm doing it for practicing...

The last thing I read about in my Learning Java books was regular expressions and List, therefore I'm writing a program to practice those to.

So, even though I suppose there are thousands of ways to improve my code, I still want to know if you can solve my problems with regular expressions, not leaving them outside and doing something else with the same effect.

/Komposten

Re: Two regular expression problems/questions

A regular expression can't recognize ordinary mathematical infix expressions; one of the causes (as you have already discovered) is those darn parentheses; i.e. they have to match for one thing and regular expressions can't do that, especially not when those parentheses are nested. It's a fundamental property of context free languages not being regular languages.

kind regards,

Jos

Re: Two regular expression problems/questions

Well I get everything to work, even with expressions such as "2*3+(9/4)" (It solves the problem according to the laws of mathematics). My biggest problem now however is that it does not read 32 as 32, but as 3 and 2 when it puts it into the array, is there a way to solve this with regular expressions, or do I have to put those together afterwards?

Like:

Code:

`array[1] = "3";`

array[2] = "2";

array[1] += array[2];

/Komposten