我从数据库中获取一个包含多个 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";
是否可以一步完成此操作,还是必须先用静态占位符替换标签和文本,然后再次替换?
最佳答案
$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') }]
)
对于任何更复杂的事情,我会结合使用语法和 Action 类。
关于search - 在 Perl6 中用彩色文本替换 HTML <i> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44589950/