Perl:重复模式 x 次,其中 x 是 \d 的匹配项

Perl: Repeat a pattern x times, where x is a match of \d

我通过

匹配了一个特定的模式和一个数字
perl -pe 's/\(pattern\)(\d)/ ... /'

我知道我可以通过将 $1 放在 ... 所在的位置以及使用 $2 来访问数字来访问该模式。我现在如何在 ... 所在的位置重复模式 $2 次? 更具体地说,我有一个像这样的表达式:

perl -pe 'while(s/Power\(((?:(?!Power\().)+?),2\)/(()*())/){}' file.txt

我想将其概括为不仅匹配 2,它在其中硬编码以重复 $1 两次,而且匹配任何数字 n 并重复 $1 n 次。所有这些仍然应该在一个班轮中完成。

因此,例如将脚本调用到

这样的表达式上
Power(Power(x,3),2)

应该return

(((x)*(x)*(x))*((x)*(x)*(x)))

您可以使用

perl -pe 'while(s/Power\(((?:(?!Power\().)+?),(\d+)\)/"((".  . ")" . ("*(" .  . ")") x (-1) . ")"/e){}' file.txt

查看在线演示:

#!/bin/bash
s='Power(25,2)  Power(225,4)'
perl -pe 'while(s/Power\(((?:(?!Power\().)+?),(\d+)\)/"((".  . ")" . ("*(" .  . ")") x (-1) . ")"/e){}' <<< "$s"
# => ((25)*(25))  ((225)*(225)*(225)*(225))

/e 标志将 RHS 视为表达式,替换是动态构建的,并且在 x operator 的帮助下进行重复。请注意,重复数量等于捕获到第 2 组的数量减去 1.