检查 Perl 正则表达式中的替换条件

Check condition in Perl regex for substitution

我想用其他字符串替换文件中的特定模式。但我只希望在模式中不匹配特定字符串时才进行替换。

我的代码如下:

use warnings;
use strict;

my $filename = 'C:\test_folder\file.txt';
my $pattern = undef;

my $read_handle = undef;
my $string = undef;

open($read_handle, "<", $filename)
        || die "[=10=]: can't open $filename for reading: $!";

while ( <$read_handle> ){
     $string = $string.$_;
}


$pattern = qr/(TEST_CASE_NAME.*?:(.*?)\n.*?PRIORITY.*?:(\w\d).*?=cut)/s;

$string =~ s{$pattern}{\n\nsub \n{\n}\n}g;
print $string;

我已将整个文件存储在一个字符串中。 我有以下问题:

If in pattern, (3rd back-reference) is not equal to "P3", then only substitution should occur. How can I achieve this?

一些输入示例数据是:

=head2 Gen_001

TEST_CASE_NAME :GEN_001
PRIORITY :P0
RELEASE_INTRODUCED :7.4 AUTOMATED :YES

STEP_NAME : step1
STEP_DESC :Example desc for understanding STEP_RESULT :Example result for understanding

=cut

=head2 Gen_003

TEST_CASE_NAME :GEN_003
PRIORITY :P1
RELEASE_INTRODUCED :7.4 AUTOMATED :NO

STEP_NAME : step1
STEP_DESC :Example desc for understanding second testcase
STEP_RESULT :Example result for understanding second testcase

=cut

=head2 Gen_004

TEST_CASE_NAME :GEN_004
PRIORITY :P3
RELEASE_INTRODUCED :7.4 AUTOMATED :NO

STEP_NAME : step1
STEP_DESC :Example desc for understanding third testcase
STEP_RESULT :Example result for understanding third testcase

=cut

您可以通过负前瞻来实现这一点:

(TEST_CASE_NAME.*?:(.*?)\n.*?PRIORITY.*?:(?!P3)(\w\d).*?=cut)
                                         ^^^^^^

demo

先行 (?!P3) 确保 (\w\d) 匹配的下两个字符不等于 P3.