Need regex pattern to capture pieces of formula
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开发者_如何学Python+,*\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.
In the middle, you have ([\/\*])
.
Try changing it to ([/*]|\*?mod)
- this will accept *
, /
, mod
and *mod
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.
精彩评论