开发者

Need regex pattern to capture pieces of formula

开发者 https://www.devze.com 2022-12-11 13:00 出处:网络
I need to extend a regex pattern in C#. The current pattern is capturing any multiplication or division in the 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号