1

I am expecting an input to look like: "x^3" and would like to replace this with a string of "pow(x, 3)". However the whole input may look like "x^3 + x^2 + 4". Here I want each instance of the "^" operator to signify a conversion to the "pow()" substring instead.

This means that the substring I am replacing it with is influenced by what it finds, but I need wildcard operators either side of the "^" if I am to do it with regular expressions.

Is there a way to "store" what the wildcard happens to be at a given instance to reinsert it in the replacement string?

i.e. in x^3, the 3 gets stored and put back into pow(x, 3)

Cases:

"x^2" -> "pow(x, 2)"

"x^3 + x^2" -> "pow(x,3) + pow(x, 2)"

"x^4 + y^19" -> "pow(x, 4) + pow(y, 19)"

Freddie R
  • 377
  • 5
  • 15
  • You can use regular expressions with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace and use a function to access the found powers. –  Jul 10 '18 at 21:00
  • @ChrisG Is each regular expression match passed into the function, or a list of all of them? – Freddie R Jul 10 '18 at 21:02

1 Answers1

6

This is the kind of problem where I'd usually use a full-on tokenizer, but yes you can use a capture group to do it:

const rewritePowers = str => str.replace(/([a-z])\^(\d+)/g, 'pow($1, $2)');

To break this down a bit, here's the matching regex:

/([a-z])\^(\d+)/g

...in which ([a-z]) captures the base variable, which we assume to be a single lowercase letter. The parenthesis capture it as a group, which means that it can be "replayed" later as $1.

Then the \^ matches the exponentation operator, (we use a backslash to escape as ^ has another meaning in regex).

Then the (\d+) captures the exponent as a second group. So the replacement string 'pow($1, $2)' just replays the captured groups.

Note that we need the /g flag on the end of the regex, otherwise this would only affect the first match in the string, and we want to replace all of them.

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20