phpregexpcrerecursive-regex

Matching Parentheses with Division Operator - Regex


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.


Solution

  • 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