PERL 正则匹配中使用变量的问题

2025-05-08 21:03:48
推荐回答(2个)
回答1:

# 将 $sentence1=~s/$w/$new/; 改成
$sentence1 =~ s/\Q$w\E/\Q$new\E/g;

你其实可以将

if ($1 eq $w){
 my $new=&gen_newname($w);
 $sentence1=~s/$w/$new/; 
 $sent1=$sentence1;
}
else {
   $sent1=$sentence1;
}

改成

$sentence1 =~ s{$w}{gen_newname($w)}eg if $w eq $1;
$sent1 = $sentence1;

回答2:

$aaa="1234,5677,3333";
$aaa=~/\d+,(\d+),\d+/; #现在$1中就是5677
print $1."\n";
$bbb="2223,4241,45452";
$bbb=~/(\d+),\d+,\d+/; #现在$1中是2223
print $1;