考虑一下这个脚本,该脚本基于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";
}
}
Run Code Online (Sandbox Code Playgroud)
给定下面的数据文件,前三行各包含一个罗马数字.
mix in here
no mix in here
mmmcmlxxxix
minimum
Run Code Online (Sandbox Code Playgroud)
当在运行macOS Sierra 10.12.4的Mac上运行(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]
Run Code Online (Sandbox Code Playgroud)
我不理解输出的唯一部分是符号^中的
插入(?^:…)符号.
我看Perl的文档
perlre和
perlref和的,甚至部分
perlop
上"正则表达式的报价般的运营商没有看到本实施或解释.(当你提出有关正则表达式的问题时,我还检查了SO建议的资源.(?^:字符串经过精心设计,可以为搜索引擎提供一些条件.)
我的问题分为两部分:
(?^:…)什么以及是什么原因导致它被添加到正则qr//表达式中?qr//表达式?基本上它意味着默认标志适用(即使它被内插到指定不同的正则表达式).在它被引入之前,qr会产生类似的东西,(?-ismx:并且Perl中会添加一个新标志来进行更改,这样可以使测试更新到最新.
http://perldoc.perl.org/perlre.html#Extended-Patterns:
从Perl 5.14开始,在"?"之后立即出现"^"(插入符号或抑扬音).是d-imnsx的简写.标志("d"除外)可以跟随插入符号覆盖它.但减号不合法.
这意味着"将所有标志(例如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
Run Code Online (Sandbox Code Playgroud)
它主要用于表示由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
Run Code Online (Sandbox Code Playgroud)