【问题标题】:Replace HTML <i> tags with colored text in Perl6在 Perl6 中用彩色文本替换 HTML <i> 标签
【发布时间】:2017-06-16 13:03:11
【问题描述】:

我从具有多个 HTML 标记的数据库中获取一个字符串,并希望在终端中用颜色显示标记的单词。我用 Perl6 试过这个,但找不到可行的解决方案。以下是我尝试过的步骤:

use v6;

use Terminal::ANSIColor;

my $str  = "Text mit einem <i>kursiven</i>  und noch einem <i>schrägen</i> Wort.";
my $str1 = "Text mit einem { colored( "kursiven" , 'blue') }  und noch einem { colored( "schrägen" , 'blue') }  Wort.";

say "\nOriginal String:";
say $str ~ "\n";

say "and how it should look like:";
say $str1 ~ "\n";

say "Var 01: Remove the tags in 2 steps:";
my $str_01 = $str.subst("<i>" , "" , :g).subst("</i>" , "" , :g);
say $str_01;
say "==> ok\n";

say "Var 02: Remove the tags with dynamic content:";
my $str_02 = $str.subst(/"<i>"(.*?)"</i>"/ , -> { $0 } , :g);
say $str_02;
say "==> ok with non greedy search\n";

say "Var 03: Turns static content into blue:";
my $str_03 = $str.subst(/"<i>kursiven</i>"/ , -> { colored( "kursiven" , 'blue') } , :g);
say $str_03;
say "==> nearly ok but second part not replaced\n";

say "Var 04: Trying something similar to Var 01:";
my $str_04 = $str.subst("<i>" , "\{ colored\( \"" , :g)
                 .subst("</i>" , "\" , 'blue'\) }" , :g);
say $str_04;
say "==> final String is ok but the \{ \} is just displayed and not executed !!\n";


say "Var 05: Should turn dynamic content into blue";
my $str_05 = $str.subst(/"<i>(.*?)</i>"/ , -> { colored( $0 , 'blue') } , :g);
say $str_05;
say "==> total fail\n";

是否可以一步完成,还是我必须先用静态占位符替换标签和文本,然后再替换?

【问题讨论】:

  • 标签中可能有 s/eval/regex/?

标签: search replace colors eval raku


【解决方案1】:
$str.subst(

    :global,

    /

        '<i>' ~ '</i>' # between these two tags:

            ( .*? )    # match any character non-greedily

    /,

    # replace each occurrence with the following
    Q:scalar[{ colored( "$0" , 'blue') }]

)

对于更复杂的事情,我会使用结合动作类的语法。

【讨论】:

  • 我收到警告“在字符串上下文中使用 Nil ...”,它也没有给出任何结果。为了得到 $0 作为替代品,我必须写 -> { $0} 。这同样适用于对“colored”的函数调用。但这对两者都不起作用。
  • @Brad-Gilbert,不错的答案。请考虑在 cmets 或您的答案中添加一两句话,说明您为什么使用 Q:scalar[{ colored( "$0" , 'blue') }] 而不仅仅是简单的 { colored( "$0" , 'blue') },正如 @user2944647 所建议的那样。
【解决方案2】:

在玩过 Brads 的回答后,我发现以下工作:

$str.subst(

    :global,

    /

        '<i>' ~ '</i>' # between these two tags:

            ( .*? )    # match any character non-greedily

    /,

    # replace each occurrence with the following
    { colored( "$0" , 'blue') }

)

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2011-03-13
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多