$search_32bit = '80 71 C3 (S{8}) (77 55 66)';
$search_32bit =~ s/s+//g;
$replace_32bit = 'A0 B0 C0 12';
$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 12';
$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";
}
我的问题是,如何保存搜索部分($r->[0])和替换部分($r->[1])的匹配部分?
谢谢。
哦,对不起,我刚找到解决方案,我把这个简单的问题复杂化了。
只需要在替换前将$hex保存为$hex_tmp,当$s_sign = 1时,则$hex_tmp为搜索部分,替换后的$hex为替换部分。
$search_32bit = '80 71 C3 (S{8}) (77 55 66)';
$search_32bit =~ s/s+//g;
$replace_32bit = 'A0 B0 C0 12';
$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 12';
$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_tmpn";
print "replaced part: $hexn";
exit();
}
}
下面是我想要的输出。
搜索部分:8071C312345678775566已更换部件:A0B0C012345678775566
参考https://www.perlmonks.org/?node_id=1006930,另一个用/ee代替'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_tmpn";
print "replaced part: $hexn";
exit();
}
}
下面得到相同的输出。
搜索部分:8071C312345678775566已更换部件:A0B0C012345678775566
如果需要捕获匹配的搜索部分而不是整个字符串,可以参考下面的代码。
$search_32bit = '(80 71 C3 (S{8}) (77 55 66))';
$search_32bit =~ s/s+//g;
$replace_32bit = 'A0 B0 C0 23';
$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 = "9090908071C312345678775566";
foreach my $r (@repls_32) {
$hex_tmp = $hex;
$s_sign = eval "$hex =~ s/$r->[0]/$r->[1]/i;return $1";
if ($s_sign) {
print "search part: $s_signn";
print "original: $hex_tmpn";
print "replaced part: $hexn";
exit();
}
}
请使用"return $1"在下面的正则表达式中,不要使用$&,因为后者是全局变量,在一些复杂的情况下会遇到问题。
$s_sign = eval "$hex =~ s/$r->[0]/$r->[1]/i;return $1";
相应的、
$search_32bit = '80 71 C3 (S{8}) (77 55 66)';
=>
$search_32bit = '(80 71 C3 (S{8}) (77 55 66))';
请注意最外层的括号。
希望对遇到类似问题的朋友有所帮助。