在 Perl 中将 (string) ^ 2 替换为 sqrt (string) [英] Replacing ( string ) ^ 2 to sqrt ( string ) in Perl
问题描述
给定的字符串(称为$bbb
!)包含许多操作数和运算符.我想替换每次出现muth ( math ) ^ 2 mith
到 muth sqrt( math ) mith
.(空格可以不止一个).
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).
假设,在整个表达式中,只有一个 (简单线性表达式)^ 2
或没有——如果这样更容易的话.
Assume that, in the entire expression, there is only either one (simple linear expression) ^ 2
or none --if it makes it easier.
包容性示例:
1.2 * ( 4.7 * a * ( b - 0.02 ) ^ 2 * ( b - 0.02 + 1 )/( b - 0.0430 ) )
应改为:
1.2 * ( 4.7 * a * sqrt( b - 0.02 ) * ( c - 0.02 + 1 )/( d - 0.0430 ) )
推荐答案
嗯...奇怪的问题...
Well... weird problem...
试试这个有点高级表达
(?<math>\((?:[^()]+|(?&math))*\))\s*\^\s*2
希望图表能说明正在发生的事情
Hopefully the graphic illustrates what's going on
替换字符串必须是 sqrt $1
perl 中的命令看起来像
The command in perl would look like
$bbb =~ s/(?<math>\((?:[^()]+|(?&math))*\))\s*\^\s*2/sqrt $1/
可以在此处找到运行示例:http://regex101.com/r/qU8dV0/3
A running example can be found here: http://regex101.com/r/qU8dV0/3
关于这到底是什么东西的一些话
这里的主要结构是anything\s*\^\s*2
,它匹配任何后跟^2
the main structure here is anything\s*\^\s*2
, it's matching anything followed by ^2
(?
构建一个名为math
的模式\(...\)
模式math
必须以左括号开始,以右括号结束- 括号内:
[^()]+
允许使用除括号之外的任何内容或(?&math)
括号中的另一个包含已定义结构的术语是允许的,因此外部模式math
是递归重复
(?<math>...)
builds a pattern namedmath
\(...\)
the patternmath
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 patternmath
is recursively repeated
这篇关于在 Perl 中将 (string) ^ 2 替换为 sqrt (string)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!