Check condition in Perl regex for substitution -
i want substitute particular pattern in file other string. want substitution when particular string not matched in pattern.
my code follows:
use warnings; use strict; $filename = 'c:\test_folder\file.txt'; $pattern = undef; $read_handle = undef; $string = undef; open($read_handle, "<", $filename) || die "$0: can't open $filename reading: $!"; while ( <$read_handle> ){ $string = $string.$_; } $pattern = qr/(test_case_name.*?:(.*?)\n.*?priority.*?:(\w\d).*?=cut)/s; $string =~ s{$pattern}{$1\n\nsub $2\n{\n}\n}g; print $string;
i have stored whole file in string. have following problem:
if in pattern, $3(3rd back-reference) not equal "p3", substitution should occur. how can achieve this?
some sample data input is:
=head2 gen_001
test_case_name :gen_001
priority :p0
release_introduced :7.4 automated :yesstep_name : step1
step_desc :example desc understanding step_result :example result understanding=cut
=head2 gen_003
test_case_name :gen_003
priority :p1
release_introduced :7.4 automated :nostep_name : step1
step_desc :example desc understanding second testcase
step_result :example result understanding second testcase=cut
=head2 gen_004
test_case_name :gen_004
priority :p3
release_introduced :7.4 automated :nostep_name : step1
step_desc :example desc understanding third testcase
step_result :example result understanding third testcase=cut
you can achieve negative lookahead:
(test_case_name.*?:(.*?)\n.*?priority.*?:(?!p3)(\w\d).*?=cut) ^^^^^^
see demo
the lookahead (?!p3)
makes sure next 2 characters matched (\w\d)
not equal p3
.
Comments
Post a Comment