考虑这个脚本,它是基于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文档的perlre
,
perlref
,还有
perlop
中关于“正则引用运算符”的部分,但没有看到这个例子或者解释。(当我在SO上问有关正则表达式的问题时,我也检查了建议的资源。 (?^:
字符串被精心设计以使搜索引擎感到困扰。)
我的问题有两个方面:
(?^:…)
中的符号^
的意义是什么?它是如何被添加到qr//
正则表达式中的?- 如果有影响,如何阻止它被添加到
qr//
正则表达式中?