2017-06-16 70 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') } 

)