在perl中使用正则表达式匹配的奇怪问题,备用尝试匹配

前端之家收集整理的这篇文章主要介绍了在perl中使用正则表达式匹配的奇怪问题,备用尝试匹配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请考虑以下perl脚本:

#!/usr/bin/perl

 my $str = 'not-found=1,total-found=63,ignored=2';

 print "1. matched using regex\n" if ($str =~ m/total-found=(\d+)/g);
 print "2. matched using regex\n" if ($str =~ m/total-found=(\d+)/g);
 print "3. matched using regex\n" if ($str =~ m/total-found=(\d+)/g);
 print "4. matched using regex\n" if ($str =~ m/total-found=(\d+)/g);

 print "Bye!\n";

运行此后的输出是:

1. matched using regex
3. matched using regex
Bye!

相同的正则表达式匹配一次,之后不匹配.任何想法为什么备用尝试匹配同一个字符串与相同的正则表达式在perl中失败?

谢谢!

解决方法

摆脱m和g作为你的正则表达式的修饰语,他们没有做你想要的.

print "1. matched using regex\n" if ($str =~ /total-found=(\d+)/);
print "2. matched using regex\n" if ($str =~ /total-found=(\d+)/);
print "3. matched using regex\n" if ($str =~ /total-found=(\d+)/);
print "4. matched using regex\n" if ($str =~ /total-found=(\d+)/);

具体来说,m在这种情况下是可选的m / foo /与/ foo /完全相同.真正的问题是g在这种情况下会做一些你不想要的东西.有关详情,请参见perlretut.

猜你在找的Perl相关文章