【发布时间】:2021-02-27 21:30:49
【问题描述】:
更新:更正下方添加的代码
我有一个名为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;
}
包含正则表达式的行给出 无法修改不可变 Pair (lang => True) 错误。
我刚刚开始使用正则表达式。而不是([a-z]+),我尝试了(\w),但它给出了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"}
【问题讨论】:
-
您可能希望在 for 循环中使用
<->而不仅仅是-> -
现在试了一下(操作员
<->)它给了参数'$key'期望一个可写容器(变量)作为参数,但得到'0'(Int)作为没有容器的值。 错误。 -
亲爱的@user0721090601 ...请您说明原因节拍->并参考相关文档页面(我找不到)
-
@p6steve 这是doc'd here。 (我通过在文档搜索框中输入
<->找到它;也许它已被添加到搜索索引中以响应您的评论?)
标签: regex markdown raku github-flavored-markdown