Regex: match an operation between two factors in mathematical equation

I want to make a regex to match either of multiplication or division operation in mathematical equation which may contain power symbol (^). The match begin between the factor within the most brackets and its nearby variable. I have created my own regex but I faced two main problems:

  1. It doesn’t match two factors that not contain * symbol between them (see example 2), I want it match.
  2. It match the operation that only contain - symbol (example 4), I want it doesn’t except there is * or / symbol before - symbol (example 3).

Here are my experiments:

EXAMPLE 1

String:

(sdf^sdf*(sdf*(23^3s)))*sdf

Expected result:

(sdf*(23^3s))

My current result:

(sdf*(23^3s))

EXAMPLE 2

String

(232^23)dfdf+dfd(sfsf)

Expected Result

(232^23)dfdf

My current result:

(doesn’t match at all)

EXAMPLE 3

String

dfd(sfsf^sdf+323)/-13+sfdfsdf

Expected Result (UPDATED)

dfd(sfsf^sdf+323)

My current result

(sfsf^sdf+323)/-13

EXAMPLE 4

String

(dfd^23sdf)-(234^dfd)

Expected Result

(doesn’t match anything)

My current result

(dfd^23sdf)-(234^dfd)

EXAMPLE 5

String

(dfd^23sdf)-(234^dfd)*(x-3)

Expected Result

(234^dfd)*(x-3)

My current result

(dfd^23sdf)-(234^dfd)*(x-3)

Here is my regex:

(-?)(?(((-?)-?d*.?d*[a-z]*^?)+))?(*?/?)((-?)(([^()]+)))(*?/?)(-?)(?(((-?)-?d*.?d*[a-z]*^?)+))|(((-?)(([^()]+)))([*/])(-?)(((?!+)(-?)(?[-d.w^+-*/]*)?))?)

Answer

After few hours of finding solution, here is what I got:

I write down the regex to match operation like (*), (/), (*-), or (/-).

(((/)(?!-))|((*)(?!-))|(/-)|(*-))?

After that, I make a regex to find the factor within the most brackets and its closest back variable which match the condition.

(((w+^(.*?)|([w^]+))|((?(([^()]+)))?))(((/)(?!-))|((*)(?!-))|(/-)|(*-))?(([^()]+)))

If it doesn’t match, then try again to find the factor within the most brackets and its closest front variable which match the condition.

((([^()]+))((((/)(?!-))|((*)(?!-))|(/-)|(*-))?((w+^(.*?)|([w^]+))|((?(([^()]+)))?))))

Then, combine those two regexs above using OR (|) quantifier to get the desired result.

DEMO

UPDATED

I modified some parts, so it can match negative factor and decimal (marked with ‘.’ symbol).

DEMO