有一个程序使用正则表达式,但不知何故我无法理解它。
代码是这样的:
@listOfIds = &methodToGetIDs();
foreach my $id (@listOfIds){
if($class =~ /gen/ig){
#does stuff
}
}
我的理解是,如果 $class
有 "gen"
那么它将进入 if{}
但有时它不会'没有进入其中,所以我添加了一个 else 来查看发生了什么,代码最终如下所示:
my $class = "genes";
foreach my $id (@listOfIds){
if($class =~ /gen/ig){
print $class."\n"; #to see the value of class
}else{
print "!!!".$class."\n"; #to see the difference if there's any
}#miss this wooops!
}
你猜怎么着?输出是这样的:
genes
genes
!!!genes
genes
genes
!!!genes
genes
genes
!!!genes
如果$class
的值没有改变那么为什么它会进入else子句?我猜我根本不懂正则表达式。有什么线索吗?
最佳答案
因为您使用的是 /g
选项。来自 perlop :
In scalar context, each execution of
m//g
finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using thepos()
function; see pos. A failed match normally resets the search position to the beginning of the string, ...
因此,您第一次查看字符串时就会得到匹配项。然后,下次您将在第一场比赛的位置之后开始。 IE。该位置不会重置为字符串的开头,而是在第一个匹配发生的位置继续。
/g
标志用于指示您想要匹配字符串中的所有次。这对于计算子字符串在字符串中出现的次数很有用。就您而言,您正在测试模式是否完全匹配,是否正确,如果匹配,则执行某些操作。在这种情况下,您不需要 /g
标志。
my $class = "genes";
foreach my $id (1..6){
if($class =~ /gen/ig){
print $class."\n"; #to see the value of class
}else{
print "!!!".$class."\n"; #to see the difference if there's any
}
}
输出:
genes
!!!genes
genes
!!!genes
genes
!!!genes
如果你删除 /g
标志,你会得到:
genes
genes
genes
genes
genes
genes
关于regex - 有人能给我解释一下 Perl 中的这个正则表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44014121/