1

Currently have /([^\s\+\(]+)\^([^\s\,\+\)]+)/g to convert x^y into pow(x,y).

Works for:

y = x 
y = x^2 
y = x^2 + y^2
y = 5*(x^2 + y^2)
y = (x^2 + y^2)
y = pow(x^2+y^2, 2)

However I want to be able to do something like this:

y = abs(x)^2 --> y = pow(abs(x), 2)

I currently have \( in the first negated capture group to stop 5*(x^2) being messed up, however what I really want to do is negate *( as a pair, so the bracket is only negated when preceded by parantheses.

Is there a way to negate specific occurences of consequtive characters?

Freddie R
  • 377
  • 5
  • 15
  • Why are you doing this? Make the formulas look nicer or for prepare it for the actual calculation? If the latter is the case, take a look at [math.js](http://mathjs.org/). – wp78de Jul 17 '18 at 23:32
  • @wp78de it is for actual calculation, but I'm running it in an environment where I don't have access to external libraries (OpenProcessing). I am also trying to further my understanding of regular expressions. – Freddie R Jul 17 '18 at 23:38

1 Answers1

1

We could avoid advanced regex features altogether and add a simple alternation for the function parameter:

(\w+\([^\s+()]+\)|[^\s+()]+)\^(\w+\([^\s+()]+\)|[^\s,+()]+)

Actually, this should not only be added to the first parameter since the second parameter could be a function as well.

Demo

The basic idea here is to capture functions and regular parameters separately.

  • ( capture group 1
  • (\w+\([^\s+()]+\) captures a function like abs(-4):
    • \w+ looking for one or more alphanum letters ([a-zA-Z0-9_])
    • ( followed be an literal opening parenthesis
    • [^\s+()]+ then, the content: everything that is not white-space or ()
    • \) and a closing parenthesis.
  • | alternation
  • [^\s+()]+ regular parameter
  • ) closing $1

then the \^ followed by the second capture group that applies the same approach.

wp78de
  • 18,207
  • 7
  • 43
  • 71