【问题标题】:Javascript regex to find expression in a line then append to the end of that line [closed]Javascript正则表达式在一行中查找表达式然后附加到该行的末尾[关闭]
【发布时间】:2016-01-04 11:23:30
【问题描述】:

我正忙于将文本日志解析为 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&lt;ul&gt;

我该怎么做?

【问题讨论】:

  • 你使用的是原生 js?
  • 嗨,我正在使用 node.js

标签: javascript regex


【解决方案1】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2012-03-19
    • 2017-07-01
    相关资源
    最近更新 更多