当我regex使用捕获组创建变量时,整个匹配是正常的,但捕获组是Nil.
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / $rgx / ;
say ~$/; # 12abc34
say $0; # Nil
say $1; # Nil
Run Code Online (Sandbox Code Playgroud)
如果我修改程序以避免$rgx,一切都按预期工作:
my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;
$str ~~ / ($atom) \w+ ($atom) /;
say ~$/; # 12abc34
say $0; # ?12?
say $1; # ?34?
Run Code Online (Sandbox Code Playgroud)
使用您的代码,编译器会发出以下警告:
Regex object coerced to string (please use .gist or .perl to do that)
Run Code Online (Sandbox Code Playgroud)
这告诉我们一些事情是错的 - 正则表达式不应该被视为字符串.嵌套正则表达式还有两种正确的方法.首先,您可以在assertions(<>)中包含子正则表达式:
my $str = 'nn12abc34efg';
my Regex $atom = / \d ** 2 /;
my Regex $rgx = / (<$atom>) \w+ (<$atom>) /;
$str ~~ $rgx;
Run Code Online (Sandbox Code Playgroud)
请注意,我不匹配/ $rgx /.那就是把一个正则表达式放在另一个正则表达 只是匹配$rgx.
更好的方法是使用命名的正则表达式.定义atom和正则表达式如下会让你访问比赛团体为$<atom>[0]和$<atom>[1]:
my regex atom { \d ** 2 };
my $rgx = / <atom> \w+ <atom> /;
$str ~~ $rgx;
Run Code Online (Sandbox Code Playgroud)