是否有可能在 perl 替换正则表达式模式中反向引用重复组

Is it possible backreference to repeated group in perl subsitution regexp pattern

我运行脚本是这样的:

echo "0x4e46436b|0x6669746f|0x74616369|0x416e6f69|0x624f796e|0x7463656a"|perl -pe 's/0x([\da-f]{2}){4}/0x/g'

我得到了这个:

0x6b|0x6f|0x69|0x69|0x6e|0x6a

如何修复脚本以获得这样的结果:

0x6b43464e|0x6f746966|0x69636174|0x696f6e41|0x6e794f62|0x6a656374

谢谢!


备选方案:perl -pe's/0x\K([\da-f]{8})/ 解压 "H*",打包 "V",十六进制 $1 /eg' –池上

感谢池上!这对我来说是 b运行d 替代的新用法。有效!

您可以从替换模式中引用的组数限制为模式中定义的捕获组数。查看有关 repeated capturing groups here 的更多详细信息。 0x([\da-f]{2}){4} 模式中只有 1 个捕获组,这意味着您不能在替换模式中使用 </code> 或 <code> 占位符。

您可以使用多个捕获组,因为您有一个 固定的 重复次数({4} 量词只设置了四个):

echo "0x4e46436b|0x6669746f|0x74616369|0x416e6f69|0x624f796e|0x7463656a" | \
  perl -pe 's/0x([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})/0x/g'

online demo

请注意,使用 perl 时,替换模式中的占位符是 advised to use $n notation