下面的输出是由第三方工具生成的,该工具根据 XML 架构验证 XML 文件。它将输出验证错误。好的,这只是一个小背景。
从上面的错误显示在 HTML 中,我希望能够使用 perl 执行“语法高亮显示”。例如,我希望能够突出显示上面文本的某些部分。
具体来说,我想将符合“Line [0-9]*”的任何文本着色为粗体和红色。我尝试过使用正则表达式搜索和替换进行试验,但没有那么成功。
任何指示/提示都会很棒。
谢谢!
Line 8: Element 'alphabet', attribute 'letters': The value 'XYZ' does not match the fixed value constraint 'ABC'.
Line 185: Element 'drink': The attribute 'coffee' is required but missing.
Line 254: Element 'timeout': This element is not expected.
Line 269: Element 'commands': This element is not expected. Expected is one of ( eat, drink, sleep ).
Line 812: Element 'software': The attribute 'version' is required but missing.
Line 876: Element 'windows-software': The attribute 'version' is required but missing.
Line 890: Element 'contact': The attribute 'telephone' is required but missing.
Line 890: Element 'operating': The attribute 'mode' is required but missing.
最佳答案
试试这个:
#!/usr/bin/perl
use strict;
use warnings;
while(<DATA>) {
s#(Line \d+)#<span style="font-weight:bold;color:red;">$1</span>#;
s#(Element\s|attribute\s)('[^']*')#$1<span style="font-weight:bold;color:blue;">$2</span>#g;
print
}
__DATA__
Line 8: Element 'alphabet', attribute 'letters': The value 'XYZ' does not match the fixed value constraint 'ABC'.
Line 185: Element 'drink': The attribute 'coffee' is required but missing.
Line 254: Element 'timeout': This element is not expected.
输出
<span style="font-weight:bold;color:red;">Line 8</span>: Element <span style="font-weight:bold;color:blue;">'alphabet'</span>, attribute <span style="font-weight:bold;color:blue;">'letters'</span>: The value 'XYZ' does not match the fixed value constraint 'ABC'.
<span style="font-weight:bold;color:red;">Line 185</span>: Element <span style="font-weight:bold;color:blue;">'drink'</span>: The attribute <span style="font-weight:bold;color:blue;">'coffee'</span> is required but missing.
<span style="font-weight:bold;color:red;">Line 254</span>: Element <span style="font-weight:bold;color:blue;">'timeout'</span>: This element is not expected.
您可以使用 css 类代替样式属性。
s#(Line \d+)#<span class="bold_red">$1</span>#;
关于html - 使用 Perl 编辑 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4499338/