Page 1 of 1

Pattern question: recursion in parentheses

Posted: Thu Mar 02, 2006 7:46 am
by zzattack
I was thinking of how to rip apart mathematical equations. The only seperators would be plus and minus signs, but the beginning of a new part only starts if the sign isn't within parentheses.

That would mean 5*sin(6)+3*sin(2*tan(4)) would capture 5*sin(6) and +3*sin(2*tan(4)).

I didn't expect regular expressions to help me out here, but then I found some info regarding (?R) and (?1)/(?2). I also found an example:

Code: Select all

\( ( (?>[^()]+) | (?R) )* \)
and it even worked if I didn't alter it. Now my question is, how can I for example also match the part in front of the parentheses pairs? If I just add ([^(])* in front of it, it seems (?R) gets messed up, and putting another pair of capturing parentheses around the \(...\) part and changing the (?R) to (?1) or (?2) doesn't work either.

I would appreciate any help, thanks in advance :)

Posted: Thu Mar 02, 2006 11:50 am
by feyd
I wouldn't use regex for math parsing. Instead, I'd use a stack parser that walks the string creating an RPN (reverse polish notation) set of registers and operations to perform.