2017-06-16 69 views
2

我从具有多个HTML标签的数据库中获取字符串,并希望在终端中显示带有颜色的标记字。我用Perl6试过,但找不到工作解决方案。下面是步骤,我想:用Perl6中的彩色文本替换HTML <i>标签

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"; 

是否有可能做到这一点在一个步骤或我确实有先用一个静态的占位符代替标签和文本,然后再更换呢?

+0

也许S/EVAL /正则表达式/在标签? – raiph

回答

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

) 

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

+0

我收到警告“在字符串上下文中使用Nil ...”并且它也没有结果。为了得到$ 0作为替换,我必须写 - > {$ 0}。这同样适用于调用“彩色”的函数。但它不适用于两者。 – user2944647

+0

@布拉德吉尔伯特,尼斯答案。请考虑在评论中或在你的答案中加入一句或两句关于你为什么使用'Q:scalar [{colored(“$ 0”,'blue')}]'而不是简单的'{colored(“$ 0” ,'blue')}',如@ user2944647所示。 – raiph

2

与布拉德斯答案打后,我发现了以下工作:

$str.subst(

    :global, 

    /

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

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

    /, 

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

)