我正忙着将文本日志解析为HTML,我正在用HTML子弹标签替换标签
我需要一个正则表达式来标识一行的开头,然后在它的末尾添加一些东西。例如:
config system accprofile
edit "Number 1"
set mntgrp read-write
edit "read-only"
set mntgrp read
config system 2
edit "Number 2"
set mntgrp read-write
edit "read-only"
set mntgrp read
需要改为:
<ul>
<li>config system accprofile</li>
<ul>
<li>edit "Number 1"</li>
<ul>
<li>set mntgrp read-write</li>
</ul>
<li>edit "read-only"</li>
<ul>
<li>set mntgrp read</li>
</ul>
</ul>
<li>config system 2</li>
<ul>
<li>edit "Number 2"</li>
<ul>
<li>set mntgrp read-write</li>
</ul>
<li>edit "read-only"</li>
<ul>
<li>set mntgrp read</li>
</ul>
</ul>
</ul>
我可以通过搜索'config'来识别每行的前面,但我需要将\n\t<ul>
附加到该行的末尾。
我该怎么做?
答案 0 :(得分:0)
你可以这样做:
function myReplaceMethod (text) {
console.clear();
text = text.replace(/^(?:\t| {4}){2}(?!\s)(.*)/gm, '\t\t\t<li>$1</li>');
text = text.replace(/^(?:\t| {4}){1}(?!\s)(.*)/gm, '\t\t<li>$1</li>\n\t\t\t<ul>');
text = text.replace(/^(?!\s)(.*)/gm, '\t<li>$1</li>\n\t\t<ul>');
text = text.replace(/(\n(\s*)<li>.*)(?:\n(?!\2\s)|(?![\s\S]))/gm, '$1\n$2</ul>\n');
text = text.replace(/^/, '<ul>\n');
text = text.replace(/$/, '\n</ul>');
text = text.replace(/(\n(\s*)(?:\t| {4})<\/ul>\n)(?=\n)/gm, '$1$2</ul>');
return text;
};
// ---
var string =
'config system accprofile\n' +
' edit "Number 1"\n' +
' set mntgrp read-write\n' +
' edit "read-only"\n' +
' set mntgrp read\n' +
'\n' +
'config system 2\n' +
' edit "Number 2"\n' +
' set mntgrp read-write\n' +
' edit "read-only"\n' +
' set mntgrp read';
var output = myReplaceMethod(string);
console.log(output);
&#13;