正则表达式-如何在保留原始字符串的同时还替换字符串中的特定模式?

时间:2018-08-03 15:54:35

标签: regex pcre

在PCRE上下文中,说明给定的输入字符串是否如下:

peakOfPeaks(nmax)

现在,我的正则表达式为(\p{P}),替换字符串为_$1_,以使输出变为:

peakOfPeaks_(_nmax_)_

如何更改正则表达式,以便也可以保留原始字符串,使输出为:

 peakOfPeaks(nmax) peakOfPeaks_(_nmax_)_

1 个答案:

答案 0 :(得分:0)

Perl解决方案:

use Modern::Perl;

my $str = 'peakOfPeaks(nmax)';
$str =~  s/^(\P{P}+)(\p{P})(\P{P}+)(\p{P})$/$& $1_$2$3_$4_/;
say $str;

输出:

peakOfPeaks(nmax) peakOfPeaks_(nmax_)_