Perl \b词锚定 结果不对 什么原因?代码:my $i=1;my $str="2 4 6 8 10 7";for ($i..10){if ($str=~/\b$i\b/g){print "$i is fine";}else{print "$i is not fine";};$i++;};结果:1 is not fine2 is fine3 is not fine4 is fine5 is not fine6 is fine7
来源:学生作业帮助网 编辑:作业帮 时间:2024/08/27 04:48:55
![Perl \b词锚定 结果不对 什么原因?代码:my $i=1;my $str=](/uploads/image/z/13642780-4-0.jpg?t=Perl+%5Cb%E8%AF%8D%E9%94%9A%E5%AE%9A+%E7%BB%93%E6%9E%9C%E4%B8%8D%E5%AF%B9+%E4%BB%80%E4%B9%88%E5%8E%9F%E5%9B%A0%3F%E4%BB%A3%E7%A0%81%EF%BC%9Amy+%24i%3D1%3Bmy+%24str%3D%222+4+6+8+10+7%22%3Bfor+%28%24i..10%29%7Bif+%28%24str%3D%7E%2F%5Cb%24i%5Cb%2Fg%29%7Bprint+%22%24i+is+fine%22%3B%7Delse%7Bprint+%22%24i+is+not+fine%22%3B%7D%3B%24i%2B%2B%3B%7D%3B%E7%BB%93%E6%9E%9C%EF%BC%9A1+is+not+fine2+is+fine3+is+not+fine4+is+fine5+is+not+fine6+is+fine7)
Perl \b词锚定 结果不对 什么原因?代码:my $i=1;my $str="2 4 6 8 10 7";for ($i..10){if ($str=~/\b$i\b/g){print "$i is fine";}else{print "$i is not fine";};$i++;};结果:1 is not fine2 is fine3 is not fine4 is fine5 is not fine6 is fine7
Perl \b词锚定 结果不对 什么原因?
代码:
my $i=1;
my $str="2 4 6 8 10 7";
for ($i..10)
{
if ($str=~/\b$i\b/g){print "$i is fine";}else{print "$i is not fine";};
$i++;
};
结果:
1 is not fine
2 is fine
3 is not fine
4 is fine
5 is not fine
6 is fine
7 is fine
8 is not fine
9 is not fine
10 is fine
Perl \b词锚定 结果不对 什么原因?代码:my $i=1;my $str="2 4 6 8 10 7";for ($i..10){if ($str=~/\b$i\b/g){print "$i is fine";}else{print "$i is not fine";};$i++;};结果:1 is not fine2 is fine3 is not fine4 is fine5 is not fine6 is fine7
我试了一下,感觉应该是g的问题.你把g去掉就对了.
至于为什么有g的时候不对,应该是有g的时候,每次匹配都是从上次成功匹配后的位置开始,但是因为7已经在字符串最后了,后面没有8,所以匹配失败,导致下次匹配将从字符串的头开始匹配,所以10匹配成功.