如何改变 Grammar 对象中的捕获?
我正在尝试使用以下方式修改分析的语法对象中的值:
method mutate(Match:D $match --> Match:D) {
for $match.values -> $line {
when $line<content><header-toc><header><taskwiki-content><taskwiki-divider> {
say 'here';
$line<content><header-toc><header><taskwiki-content><taskwiki-divider>.replace-with('');
say $line; # has not been modified;
}
};
return $match;
}
我没有遇到任何错误,但是$ match
对象不受replace> replace with-with
的影响。我正在运行的方法。
I'm trying to modify the values in a parsed Grammar object with this:
method mutate(Match:D $match --> Match:D) {
for $match.values -> $line {
when $line<content><header-toc><header><taskwiki-content><taskwiki-divider> {
say 'here';
$line<content><header-toc><header><taskwiki-content><taskwiki-divider>.replace-with('');
say $line; # has not been modified;
}
};
return $match;
}
I'm not getting any errors but the $match
object is not affected by the replace-with
method I'm running.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能。 (嗯,您可以通过
make
将数据挂在它们上,但您不能做您认为可以做的事情。)
Match
对象存储与某个字符串匹配,任何捕获都只是该原始字符串的.from
、.to
索引。例如,如果您编写
"bar".match(/a/)
,则生成的Match
对象将存储.match
方法的调用者"bar"
,并且.from
为1
,.to
为2
它表示捕获的“a”
子字符串。原始字符串保持不可变,并且捕获的子字符串是“虚拟的”,没有任何内容可以改变。
replace-with
不会修改其调用者。它只是返回一个值(一个新的字符串)。引用
replace-with
文档,并添加我的 <强>粗体强调:请注意,它不是“调用者
Match
对象”。.replace-with
方法返回一个新的字符串,它是与匹配的原始输入字符串的副本> 生成Match
对象,并将匹配的位替换为作为.replace-with
方法参数提供的字符串。You can't. (Well, you can hang data off them via
make
, but you can't do what you're thinking you can do.)A
Match
object stores the result of a match against some string, and any captures are just.from
,.to
indexes into that original string.For example, if you write
"bar".match(/a/)
, the resultingMatch
object stores the.match
method's invocant"bar"
, and has a.from
of1
and a.to
of2
which represents the captured"a"
substring.The original string remains immutable, and the captured substrings are "virtual" as it were, with nothing you can mutate.
replace-with
does not modify its invocant. It just returns a value (a new string).Quoting the
replace-with
doc, with my added bold emphasis:Note that it's not "the invocant
Match
object".The
.replace-with
method is returning a new string that's a copy of the original input string that was matched against to produce theMatch
object, with the bit that was matched replaced by the string supplied as the.replace-with
method's argument.