开发者

Matching Parentheses with Division Operator - Regex

开发者 https://www.devze.com 2023-02-05 17:07 出处:网络
Examples: input: (n!/(1+n)) output: frac{n!}{1+n} input: ((n+11)!/(n-k)^(-1)) output: frac{(n+11)!}{(n-k)^(-1)}

Examples:

input: (n!/(1+n))
output: frac{n!}{1+n}

input: ((n+11)!/(n-k)^(-1))
output: frac{(n+11)!}{(n-k)^(-1)}

input: (9/10)
output: frac{9}{10}

input: ((n+11)!/(n-k)^(-1))+(11)/(2)
output: frac{(n+11)!}{(n-k)^(-1)}+(11)/(2)

The following regex works if there are no sub parentheses.

\(([^\/\)]*)\/([^\)]*)\)

The following does matching parentheses

开发者_开发问答
@\((([^()]++|\((?:[^()]++|(?R))+\))+)\)@

I just can not figure out how to "combine" them - write a single regex to handle division and balanced parentheses.


I think something like this should work:

((?:\w+|\((?1)\))(?:[+*^-](?1)|!)?)\/((?1))

Now, this probably isn't perfect, but here's the idea:

The first group, $1, is ((?:\w+|\((?1)\))(?:[+*^-](?1)|!)?), which is:

(A literal) or (a balanced expression wrapped in parentheses), followed by an optional operator and another balanced expression if needed.
Writing it that way, we can use (?1) anywhere in the regex to refer to another balanced expression.

Working example: http://ideone.com/PNLOD


I know you've already accepted a regexp, but the real answer to what you're trying to do is a proper parser... and no, you don't need to code this from scratch or reinvent the wheel. While a lot of people hate phpclasses, the evalMath class that you can find there is incredibly useful for parsing and evaluating mathematical formulae. See my answer to a similar question for details of how it can be used and extended.

0

精彩评论

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

关注公众号