Replacing ( string ) ^ 2 to sqrt ( string ) in Per

2019-03-07 04:54发布

问题:

A given string (called $bbb!) contains many operands and operators. I want to replace every occurrence of muth ( math ) ^ 2 mith to muth sqrt( math ) mith. (whitespace can be more than just one).

EDIT: Assume that, in the entire expression, there is only either one (simple linear expression) ^ 2 or none --if it makes it easier.

Inclusive Example:

1.2 * ( 4.7 * a * ( b - 0.02 ) ^ 2 * ( b - 0.02 + 1 ) / ( b - 0.0430 ) )

should be changed to:

1.2 * ( 4.7 * a * sqrt( b - 0.02 ) * ( c - 0.02 + 1 ) / ( d - 0.0430 ) )

回答1:

Well... weird problem...

Try it with this a bit advanced expression

(?<math>\((?:[^()]+|(?&math))*\))\s*\^\s*2

Hopefully the graphic illustrates what's going on

Debuggex Demo

The replacement string must than be sqrt $1

The command in perl would look like

$bbb =~ s/(?<math>\((?:[^()]+|(?&math))*\))\s*\^\s*2/sqrt $1/

A running example can be found here: http://regex101.com/r/qU8dV0/3


some words on what the heck, this is

the main structure here is anything\s*\^\s*2, it's matching anything followed by ^2

  • (?<math>...) builds a pattern named math
  • \(...\) the pattern math must begin with an opening parenthesis and end with a closing one
  • within the parenthesisses:
    • [^()]+ anything except parenthesisses is allowed or
    • (?&math) another in parenthesis wrapped term with the already defined structure, is allowed, so the outer pattern math is recursively repeated