gpt4 book ai didi

raku - Perl 6 正则表达式变量和捕获组

转载 作者:行者123 更新时间:2023-12-04 22:56:01 33 4
gpt4 key购买 nike

当我制作 regex带捕获组的变量,整个匹配没问题,但捕获组是 Nil .

my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;

$str ~~ / $rgx / ;
say ~$/; # 12abc34
say $0; # Nil
say $1; # Nil

如果我修改程序以避免 $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」

最佳答案

对于您的代码,编译器会发出以下警告:

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;

关于raku - Perl 6 正则表达式变量和捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46725987/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com