更新: 下文已添加更正后的代码
我有一个名为 sample.md
的Leanpub风格的Markdown文件,我想使用Raku Regex
将其中的代码块转换为Github风格的Markdown格式。
Here's a sample **ruby** code, which
prints the elements of an array:
{:lang="ruby"}
['Ian','Rich','Jon'].each {|x| puts x}
Here's a sample **shell** code, which
removes the ending commas and
finds all folders in the current path:
{:lang="shell"}
sed s/,$//g
find . -type d
为了捕获
{:lang="ruby"}
中的 lang
值,例如 ruby
,并将其转换为:```ruby
我使用这段代码
my @in="sample.md".IO.lines;
my @out;
for @in.kv -> $key,$val {
if $val.starts-with("\{:lang") {
if $val ~~ /^{:lang="([a-z]+)"}$/ { # capture lang
@out[$key]="```$0"; # convert it into ```ruby
$key++;
while @in[$key].starts-with(" ") {
@out[$key]=@in[$key].trim-leading;
$key++;
}
@out[$key]="```";
}
}
@out[$key]=$val;
}
正则表达式所在行出现了Cannot modify an immutable Pair (lang => True)的错误。
我刚开始使用正则表达式。我曾经尝试过(\w)
而不是([a-z]+)
,但是它会产生一些错误,例如Unrecognized backslash sequence: '\w'
。
如何使用正则表达式正确捕获和修改lang
值?
- LFM格式仅为估计值。
修正后的代码:
my @in="sample.md".IO.lines;
my \len=@in.elems;
my @out;
my $k = 0;
while ($k < len) {
if @in[$k] ~~ / ^ '{:lang="' (\w+) '"}' $ / {
push @out, "```$0";
$k++;
while @in[$k].starts-with(" ") {
push @out, @in[$k].trim-leading;
$k++; }
push @out, "```";
}
push @out, @in[$k];
$k++;
}
for @out {print "$_\n"}
<->
而不仅仅是->
。 - user0721090601<->
),但是出现了 参数 '$key' 期望一个可写的容器(变量)作为参数,但是得到了一个没有容器的值 '0'(Int) 的错误。 - Lars Malmsteen<->
找到它的;也许它是针对你的评论添加到搜索索引中的?) - raiph