javascript - 创建正则表达式来将 html 解析为 MXML 语法

标签 javascript regex

我在 stackoverflow 上搜索了很多,发现非常有趣,其中包括:

How to create a Regular Expression for a span attribute?

还有 Javascript regex to replace text div and < >

但事实证明,我无法真正解析我的目标,即用数据类型属性替换 div 并删除字符串上的数据类型属性。

这就是我的做法。

//Doesn't work with multi lines, just get first occurrency and nothing more.
// Regex: /\s?data\-type\=(?:['"])?(\d+)(?:['"])?/

var source_code = $("body").html();

var rdiv = /div/gm; // remove divs
var mxml = source_code.match(/\S?data\-type\=(?:['"])?(\w+)(?:['"])?/);
var rattr =source_code.match(/\S?data\-type\=(?:['"])?(\w+)(?:['"])/gm);
var outra = source_code.replace(rdiv,'s:'+mxml[1]);
var nestr = outra.replace(rattr[0],'');// worked with only first element
console.log(nestr);
console.log(mxml);
console.log(rattr);

在此 HTML 示例页面上

<div id="app" data-type="Application">
    <div data-type="Label"></div>
     <div data-type="Button"></div>
     <div data-type="VBox"></div>
     <div data-type="Group"></div>
</div>

对具体事情有任何了解吗?我可能错过了一些东西,但我真的不知道,没有剩余空间否则在这里询问。

我创建了一个jsFiddle来展示,只需打开浏览器的控制台即可看到我的结果。

http://jsfiddle.net/uWCjV/

请随意回答 jsfiddle 或对我的正则表达式的更好解释,以及它失败的原因。

在收到任何反馈之前,我将继续尝试看看是否可以设法替换文本。

提前致谢。

最佳答案

将标记解析为对象树,然后将其转换为 MXML 可能会更容易。

类似这样的事情:

var source_code = $("body").html();

var openStartTagRx = /^\s*<div/i;
var closeStartTagRx = /^\s*>/i;
var closeTagRx = /^\s*<\/div>/i;
var attrsRx = new RegExp(
    '^\\s+' +
    '(?:(data-type)|([a-z-]+))' +    // group 1 is "data-type" group 2 is any attribute
    '\\=' +
    '(?:\'|")' +
    '(.*?)' +                        // group 3 is the data-type or attribute value
    '(?:\'|")',
    'mi');


function Thing() {
    this.type = undefined;
    this.attrs = undefined;
    this.children = undefined;
}

Thing.prototype.addAttr = function(key, value) {
    this.attrs = this.attrs || {};
    this.attrs[key] = value;
};

Thing.prototype.addChild = function(child) {
    this.children = this.children || [];
    this.children.push(child);
};


function getErrMsg(expected, str) {
    return 'Malformed source, expected: ' + expected + '\n"' + str.slice(0,20) + '"';
}


function parseElm(str) {

    var result,
        elm,
        childResult;

    if (!openStartTagRx.test(str)) {
        return;
    }
    elm = new Thing();
    str = str.replace(openStartTagRx, '');

    // parse attributes
    result = attrsRx.exec(str);
    while (result) {
        if (result[1]) {
            elm.type = result[3];
        } else {
            elm.addAttr(result[2], result[3]);
        }
        str = str.replace(attrsRx, '');
        result = attrsRx.exec(str);
    }

    // close off that tag
    if (!closeStartTagRx.test(str)) {
        throw new Error(getErrMsg('end of opening tag', str));
    }
    str = str.replace(closeStartTagRx, '');

    // if it has child tags
    childResult = parseElm(str);
    while (childResult) {
        str = childResult.str;
        elm.addChild(childResult.elm);
        childResult = parseElm(str);
    }

    // the tag should have a closing tag
    if (!closeTagRx.test(str)) {
        throw new Error(getErrMsg('closing tag for the element', str));
    }
    str = str.replace(closeTagRx, '');
    return {
        str: str,
        elm: elm
    };
}


console.log(parseElm(source_code).elm); 

jsFiddle

这会将您提供的标记解析为以下内容:

{ 
  "type" : "Application"
  "attrs" : { "id" : "app" },
  "children" : [
    { "type" : "Label" },
    { "type" : "Button" },
    { "type" : "VBox" },
    { "type" : "Group" }
  ],
}

它是递归的,因此嵌入的组也会被解析。

关于javascript - 创建正则表达式来将 html 解析为 MXML 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641498/

相关文章:

javascript - Angular - 仅在唯一时推送到数组

javascript - 当点击没有在内容之外启动时防止模态关闭?

javascript - 在 JavaScript 函数中使用 jQuery

regex - 以正则表达式作为其结果之一的 Perl 三元语句

regex - perl 中的 "$\=$/;"是什么意思?

javascript - 用于插入的正则表达式 - 在数字中的特定索引之后

javascript - 输入期间匹配单个单词的正则表达式规则 (TipTap InputRule)

php - 在 IE(和 Firefox)中处理后退按钮的最佳实践是什么

regex - Scala 正则表达式模式提取器

php - 浏览器版本匹配 - PHP 5.1.6 中的正则表达式中断