Home > Blockchain >  How to save matched part when use 'eval' in regular expression with Perl?
How to save matched part when use 'eval' in regular expression with Perl?

Time:10-09

$search_32bit  = '80 71 C3 (\S{8}) (77 55 66)';
$search_32bit =~ s/\s //g;
$replace_32bit = 'A0 B0 C0 \1\2';
$replace_32bit =~ s/\s //g;

$search_32bit  = '60 71 C3 (\S{10}) (CC 55 66)';
$search_32bit =~ s/\s //g;
$replace_32bit = 'D0 E0 F0 \1\2';
$replace_32bit =~ s/\s //g;

        @repls_32 = (
                [ $search_32bit, $replace_32bit],
    [ $search_32bit_2, $replace_32bit_2],
                );

foreach my $r (@repls_32) {
    
    $s_sign = eval "\$hex =~ s/$r->[0]/$r->[1]/i";
    
}

My question is ,how can save the matched parts for both search part($r->[0]) and replaced part($r->[1])?

Thanks.

CodePudding user response:

Oh, sorry, just found the solution, I complicated this simple problem.

Just need save $hex with $hex_tmp before replacement, when $s_sign = 1, then $hex_tmp is the search part, and $hex after replacement is the replaced part.

$search_32bit  = '80 71 C3 (\S{8}) (77 55 66)';
$search_32bit =~ s/\s //g;
$replace_32bit = 'A0 B0 C0 \1\2';
$replace_32bit =~ s/\s //g;

$search_32bit_2  = '60 71 C3 (\S{10}) (CC 55 66)';
$search_32bit_2 =~ s/\s //g;
$replace_32bit_2 = 'D0 E0 F0 \1\2';
$replace_32bit_2 =~ s/\s //g;

        @repls_32 = (
                [ $search_32bit, $replace_32bit],
                [ $search_32bit_2, $replace_32bit_2],
                );

$hex = "8071C312345678775566";

foreach my $r (@repls_32) {
        $hex_tmp = $hex;
        $s_sign = eval "\$hex =~ s/$r->[0]/$r->[1]/i";
        if ($s_sign) {
                print "search part: $hex_tmp\n";
                print "replaced part: $hex\n";
                exit();
        }
}

Below is the output I want.

search part: 8071C312345678775566 replaced part: A0B0C012345678775566

CodePudding user response:

Reference https://www.perlmonks.org/?node_id=1006930, another sulution with /ee to replace 'eval'.

$search_32bit  = '80 71 C3 (\S{8}) (77 55 66)';
$search_32bit =~ s/\s //g;
$replace_32bit = 'A0 B0 C0 .$1.$2';
$replace_32bit =~ s/\s //g;

$search_32bit_2  = '60 71 C3 (\S{10}) (CC 55 66)';
$search_32bit_2 =~ s/\s //g;
$replace_32bit_2 = 'D0 E0 F0 .$1.$2';
$replace_32bit_2 =~ s/\s //g;

        @repls_32 = (
                [ $search_32bit, $replace_32bit],
                [ $search_32bit_2, $replace_32bit_2],
                );

$hex = "8071C312345678775566";

foreach my $r (@repls_32) {

        $hex_tmp = $hex;
        $s_sign = $hex =~ s/$r->[0]/$r->[1]/iee;
        if ($s_sign) {
                print "search part: $hex_tmp\n";
                print "replaced part: $hex\n";
                exit();
        }
}

Below get the same output.

search part: 8071C312345678775566 replaced part: A0B0C012345678775566

  • Related