该pos()
函数可用于报告匹配的(结束)位置。例子:
my $string = 'abcdefghijk';
if($string =~ /e/g)
{
print "There is an 'e' ending at position ", pos($string), ".\n";
}
此代码将打印,“在位置 5 处有一个 'e' 结尾。” (位置从 0 开始。)将此与捕获括号的正常使用结合起来,您应该能够解决您的问题。
除了 之外pos()
,还有特殊的全局数组@-
,@+
它们提供每个匹配的子模式的开始和结束偏移量。例子:
my $string = 'foo bar baz';
if($string =~ /(foo) (bar) (baz)/)
{
print "The whole match is between $-[0] and $+[0].\n",
"The first match is between $-[1] and $+[1].\n",
"The second match is between $-[2] and $+[2].\n",
"The third match is between $-[3] and $+[3].\n";
}
(感谢 Chas. Owens 让我记忆犹新;我在寻找perlre
它们而不是在perlvar
寻找它们)