perl6 – Perl 6正则表达式变量和捕获组
发布时间:2020-12-15 23:22:53 所属栏目:大数据 来源:网络整理
导读:当我使用捕获组创建正则表达式变量时,整个匹配是正常的,但捕获组是Nil. my $str = 'nn12abc34efg';my $atom = / d ** 2 /;my $rgx = / ($atom) w+ ($atom) /;$str ~~ / $rgx / ;say ~$/; # 12abc34say $0; # Nilsay $1; # Nil 如果我修改程序以避免$rgx,一
当我使用捕获组创建正则表达式变量时,整个匹配是正常的,但捕获组是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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |