tags:

views:

48

answers:

2

I need to extend a regex pattern in C#. The current pattern is capturing any multiplication or division in the formula:

([\+-]?\d+,*\d*[eE][\+-]?\d+|[\-\+]?\d+,*\d*)([\/\*])(-?\d+,*\d*[eE][\+-]?\d+|-?\d+,*\d*)

That means that if the expression is e.g. 12+18*3+4-3/3, it will capture 18*3 and -3/3. That is great.

Now I need to extend it, so that it captures the following example: 12+18*3+4-3/3+10*mod8. It should first capture 18*3, then -3/3, as it did so far, but then it should capture 10mod8 (or 10*mod8). How can I achieve this? Thanks.

+1  A: 

In the middle, you have ([\/\*]).
Try changing it to ([/*]|\*?mod) - this will accept *, /, mod and *mod

Kobi
This is refreshing. Anonymous downvotes for a correct solution that answers the OP's question... Guess I should have been more educating :)
Kobi
Sorry about that, it appears that was me, or better: my uncontrollable trigger-finger... I've undone the "mis-click"! :)
Bart Kiers
Kobi, you're the man! Thanks a bunch, it works like a charm. I've added my comment to the question's comments section with the explanation why I needed this functionality.
Boris
@Bart - that's cool, just virtual points. I think I took it well... :)
Kobi
+1  A: 

You cannot implement some sort of operator precedence in regex. Regex just matches, or it does not. Regex also cannot handle matching nested parenthesis. The only way to do this properly is to write an expression lexer/parser or define a grammar and let a tool like ANTLR generate the lexer/parser for you.

Bart Kiers