用Perl6中的彩色文本替换HTML <i>标签

时间:2017-06-16 13:03:12

标签: search replace colors eval perl6

我从具有多个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";

是否可以一步完成此操作,还是必须先使用静态占位符替换标记和文本,然后再将其替换?

2 个答案:

答案 0 :(得分:2)

$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') }]

)

对于任何更复杂的东西,我会使用语法与动作类结合。

答案 1 :(得分: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') }

)