views:

145

answers:

4

Hello,

is there any java library in the wild which can "calculate" string:

(aaa/bbb/ccc)+ddd

into

aaa ddd, bbb ddd, ccc ddd

and can maybe "solve" nested:

(a+(b/c))/((d/e)+f)

to

a b, a c, d f, e f

Thanks

+1  A: 

I dont know of any off hand, but I would go ahead and just write the code off hand. Parse the file, find (), Split strings by /, at the end add all / strings with the + string, and it should work out.

Jim
extremely useful answer
Andrey
sounds easy peasy but wont work for sure, there are many rules you have to care about and if hes trying to solve equations with strings its quite recursive, too.
atamanroman
+1  A: 

Try a parser generator for Java such as Jack or one of the others. Parsers are a great tool in a programmer's repertoire, and those tools make them fairly easy.

justkt
A: 

I know a open source math parser from mycsharp.de which got quite good feedback, its C# but might be a good example how to go (and easy to convert). Sadly, its not only C# but german.

But there are many math parser out there, just google "math expression parser" or something like that. Have a look at lex, too!

atamanroman
+1  A: 

I assume you are trying to solve a equation. Then you can do this:

  1. Use regex to split the equation or split the string to create an array of individual chars.

  2. Use a LinkedList in Java to construct the List, follow BODMAS: search, solve and remove.

Example: 2-3+1

Regex gives: [2, -, 3, +, 1]

Insert it into a LinkedList and first search for (), then +..etc (follow BODMAS). So when + is encountered, do: -3+1, remove + and 1. Replace 3 with the sum (2).

zengr
regexps sounds like a bad idea when parenthesis are involved... (The expressions to parse are not regular!)
aioobe
Id say so, too. Afaik you cant build parser like that with regexp, the language is just too limited (has something to do with http://en.wikipedia.org/wiki/Chomsky_hierarchy)
atamanroman
answer updated.
zengr
No, I am not trying to do math.
bbcooper