Perl 6 正则表达式变量和捕获组
Perl 6 regex variable and capturing groups
当我用捕获组创建一个 regex
变量时,整个匹配没问题,但捕获组是 Nil
。
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / $rgx / ;
say ~$/; # 12abc34
say [=10=]; # Nil
say ; # Nil
如果我修改程序以避免 $rgx
,一切都按预期工作:
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / ($atom) \w+ ($atom) /;
say ~$/; # 12abc34
say [=11=]; # 「12」
say ; # 「34」
对于您的代码,编译器会给出以下警告:
Regex object coerced to string (please use .gist or .perl to do that)
这告诉我们出了点问题——正则表达式不应被视为字符串。嵌套正则表达式还有两种更合适的方法。首先,您可以在断言中包含子正则表达式(<>
):
my $str = 'nn12abc34efg';
my Regex $atom = / \d ** 2 /;
my Regex $rgx = / (<$atom>) \w+ (<$atom>) /;
$str ~~ $rgx;
请注意,我不匹配 / $rgx /
。那就是将一个正则表达式放在另一个正则表达式中。只需匹配 $rgx
.
更好的方法是使用命名正则表达式。如下定义 atom
和正则表达式将使您可以访问匹配组 $<atom>[0]
和 $<atom>[1]
:
my regex atom { \d ** 2 };
my $rgx = / <atom> \w+ <atom> /;
$str ~~ $rgx;
关键的观察是 $str ~~ / $rgx /;
是一个 "regex inside of a regex"。 $rgx
应该匹配并在它自己的 Match 对象中设置 [=14=]
和 </code>,但是周围的匹配对象中没有地方可以存储该信息,因此您看不到它。也许举个例子就很清楚了,试试这个:</p>
<pre><code>my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / [=10=]=$rgx /;
say $/;
记下[=14=]
的内容。或者作为另一个例子,让我们给它一个合适的名字:
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / $<bits-n-pieces>=$rgx /;
say $/;
当我用捕获组创建一个 regex
变量时,整个匹配没问题,但捕获组是 Nil
。
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / $rgx / ;
say ~$/; # 12abc34
say [=10=]; # Nil
say ; # Nil
如果我修改程序以避免 $rgx
,一切都按预期工作:
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / ($atom) \w+ ($atom) /;
say ~$/; # 12abc34
say [=11=]; # 「12」
say ; # 「34」
对于您的代码,编译器会给出以下警告:
Regex object coerced to string (please use .gist or .perl to do that)
这告诉我们出了点问题——正则表达式不应被视为字符串。嵌套正则表达式还有两种更合适的方法。首先,您可以在断言中包含子正则表达式(<>
):
my $str = 'nn12abc34efg';
my Regex $atom = / \d ** 2 /;
my Regex $rgx = / (<$atom>) \w+ (<$atom>) /;
$str ~~ $rgx;
请注意,我不匹配 / $rgx /
。那就是将一个正则表达式放在另一个正则表达式中。只需匹配 $rgx
.
更好的方法是使用命名正则表达式。如下定义 atom
和正则表达式将使您可以访问匹配组 $<atom>[0]
和 $<atom>[1]
:
my regex atom { \d ** 2 };
my $rgx = / <atom> \w+ <atom> /;
$str ~~ $rgx;
关键的观察是 $str ~~ / $rgx /;
是一个 "regex inside of a regex"。 $rgx
应该匹配并在它自己的 Match 对象中设置 [=14=]
和 </code>,但是周围的匹配对象中没有地方可以存储该信息,因此您看不到它。也许举个例子就很清楚了,试试这个:</p>
<pre><code>my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / [=10=]=$rgx /;
say $/;
记下[=14=]
的内容。或者作为另一个例子,让我们给它一个合适的名字:
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / $<bits-n-pieces>=$rgx /;
say $/;