在应用程序中使用perl进行正则表达式替换

时间:2015-10-14 12:51:30

标签: regex perl

我要进行正则表达式替换,我正在使用perl;看起来与此相似

  

$ ABC =〜S / APP _ *。*?_ LOG _(。*?)_ * / $ 1 /

     

打印“ABC = $ ABC \ n”;

$ABC在替换之前和之后的格式可以是以下格式:

APP_184_PRD_LOG_O2_2M -> O2
APP_184_PRD_CFC_O2_6D -> O2
APP_046_STG_CFC_BCK_4W_1 -> BCK
APP_050_STG_LOG_OSS_8M_2 -> OSS
APP_050_STG_LOG_SAM_SOX_2M -> SAM_SOX
APP_050_STG_CFC_SAM_FOR_6M_3 -> SAM_FOR

Rules:-
1st variable is always APP
4th variable can be LOG or CFC
We are concerned with variable no.5 or 6(in some cases)
If the 6th variable has Number+(W/D/M), then 6th & 7th variable to be removed

替换必须是单个衬垫(应用限制)。

3 个答案:

答案 0 :(得分:0)

您可以使用negative lookahead (?![^\d+].*?),即:

^APP.*?(?:CFC|LOG)_(.*?)_(?![^\d+].*?)

<强>样本

https://regex101.com/r/lE7oB7/1

答案 1 :(得分:0)

尝试使用否定前瞻或积极向前看

负面展望

~s/APP.+?(?:LOG|CFC)_(.+?)_(?![^\d]).+/$1/

积极向前看

~s/APP.+?(?:LOG|CFC)_(.+?)_(?=\d).+/$1/g;

while (<DATA>)
{
    $_ =~s/APP.+?(?:LOG|CFC)_(.+?)_(?![^\d]).+/$1/g;
    print $_;

}

__DATA__
APP_184_PRD_LOG_O2_2M
APP_184_PRD_CFC_O2_6D 
APP_046_STG_CFC_BCK_4W_1
APP_050_STG_LOG_OSS_8M_2 
APP_050_STG_LOG_SAM_SOX_2M 
APP_050_STG_CFC_SAM_FOR_6M_3

输出

O2
O2
BCK
OSS
SAM_SOX
SAM_FOR

答案 2 :(得分:0)

我认为这也会这样做:

s/^APP_[^_]{3}_[^_]{3}_(?:LOG|CFC)_(.+)_\d[WMD](?:_\d+)?$/$1/;

输出:

$ perl -le 'for (@ARGV) { s/^APP_[^_]{3}_[^_]{3}_(?:LOG|CFC)_(.+)_\d[WMD](?:_\d+)?$/$1/; print }' APP_184_PRD_LOG_O2_2M APP_184_PRD_CFC_O2_6D APP_046_STG_CFC_BCK_4W_1 APP_050_STG_LOG_OSS_8M_2 APP_050_STG_LOG_SAM_SOX_2M APP_050_STG_CFC_SAM_FOR_6M_3
O2
O2
BCK
OSS
SAM_SOX
SAM_FOR
$