Perl qr//正则表达式中的字符串形式中,(?^:…)中的插入符号^代表什么意思?

7
考虑这个脚本,它是基于SO 267399的答案而编写的,该答案与解析罗马数字有关,但解析罗马数字与本问题无关。请看下面的代码片段:
#!/usr/bin/env perl
#
# Based on answer to SO 0026-7399

use warnings;
use strict;

my $qr1 = qr/(?i:M{1,3})/;
my $qr2 = qr/(?i:C[MD]|D?C{1,3})/;
my $qr3 = qr/(?i:X[CL]|L?X{1,3})/;
my $qr4 = qr/(?i:I[XV]|V?I{1,3})/;

print "1000s: $qr1\n";
print " 100s: $qr2\n";
print "  10s: $qr3\n";
print "   1s: $qr4\n";

# This $qr is too simple — it matches the empty string
#my $qr = qr/($qr1?$qr2?$qr3?$qr4?)/;

my $qr = qr/\b((?:$qr1$qr2?$qr3?$qr4?)|(?:$qr2$qr3?$qr4?)|(?:$qr3$qr4?)|(?:$qr4))\b/;

print " Full: $qr\n";

while (<>)
{
    chomp;
    print " Line: [$_]\n";
    while ($_ =~ m/$qr/g)
    {
        print "Match: [$1] found in [$_] using qr//\n";
    }
}

下面是数据文件,前三行分别包含一个罗马数字。

mix in here
no mix in here
mmmcmlxxxix
minimum

在MacOS Sierra 10.12.4上运行(home-built) Perl 5.22.0时,我会得到以下输出(但Perl的版本并不重要):

1000s: (?^:(?i:M{1,3}))
 100s: (?^:(?i:C[MD]|D?C{1,3}))
  10s: (?^:(?i:X[CL]|L?X{1,3}))
   1s: (?^:(?i:I[XV]|V?I{1,3}))
 Full: (?^:\b((?:(?^:(?i:M{1,3}))(?^:(?i:C[MD]|D?C{1,3}))?(?^:(?i:X[CL]|L?X{1,3}))?(?^:(?i:I[XV]|V?I{1,3}))?)|(?:(?^:(?i:C[MD]|D?C{1,3}))(?^:(?i:X[CL]|L?X{1,3}))?(?^:(?i:I[XV]|V?I{1,3}))?)|(?:(?^:(?i:X[CL]|L?X{1,3}))(?^:(?i:I[XV]|V?I{1,3}))?)|(?:(?^:(?i:I[XV]|V?I{1,3}))))\b)
 Line: [mix in here]
Match: [mix] found in [mix in here] using qr//
 Line: [no mix in here]
Match: [mix] found in [no mix in here] using qr//
 Line: [mmmcmlxxxix]
Match: [mmmcmlxxxix] found in [mmmcmlxxxix] using qr//
 Line: [minimum]

我没能理解的部分是表示为(?^:…) 的符号 ^

我查看了Perl文档的perlreperlref,还有 perlop 中关于“正则引用运算符”的部分,但没有看到这个例子或者解释。(当我在SO上问有关正则表达式的问题时,我也检查了建议的资源。 (?^:字符串被精心设计以使搜索引擎感到困扰。)

我的问题有两个方面:

  1. (?^:…) 中的符号^的意义是什么?它是如何被添加到qr//正则表达式中的?
  2. 如果有影响,如何阻止它被添加到qr//正则表达式中?
2个回答

8
基本上意味着使用默认标志(即使它插入到指定不同的正则表达式中)。 在引入该方法之前,qr会生成类似于(?-ismx:的内容,并且添加一个新标志会改变Perl的行为,这使得保持测试的最新状态变得痛苦。 http://perldoc.perl.org/perlre.html#Extended-Patterns
从Perl 5.14开始,“^”(脱字符或插入符号)紧跟在“?”后面即表示等同于d-imnsx。除“d”以外的标志可以跟随插入符号以覆盖它。但是不能与减号一起使用。

5
这意味着“将所有标志(如 i s )设置为它们的默认值”,因此
$ perl -le'my $re = "a"; for (qw( a A )) { print "$_: ", /$re/i ? "match" : "no match"; }'
a: match
A: match

$ perl -le'my $re = "(?^:a)"; for (qw( a A )) { print "$_: ", /$re/i ? "match" : "no match"; }'
a: match
A: no match

它主要用于表示由qr//创建的模式。

$ perl -le'my $re = qr/a/; print $re; for (qw( a A )) { print "$_: ", /$re/i ? "match" : "no match"; }'
(?^:a)
a: match
A: no match

$ perl -le'my $re = qr/a/i; print $re; for (qw( a A )) { print "$_: ", /$re/i ? "match" : "no match"; }'
(?^i:a)
a: match
A: match

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接