regex为html属性匹配进行无限循环

uinbv5nw  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(100)
<(?<nodeName>[a-zA-Z][-a-zA-Z0-9_]*)(?<attributes>(?:\s*[a-zA-Z_:!0-9,][-a-zA-Z0-9_:%."'`;(]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|{{[^>}]*}}|[^>]+|\w*))?)*)\s*(\/?)>

上面的正则表达式试图匹配tagName和属性。

<span class='Utils.showtt("{{getI18n('zr.ratings.reviews.client.review.tag', getCrmModuleInfo('Accounts', 'true'))}}")'>

但由于输入中的引号不匹配而导致无限循环。有什么方法可以抛出错误或防止无限循环。

w51jfk4q

w51jfk4q1#

<(?<nodeName>[a-zA-Z][-a-zA-Z0-9_]*)(?<attributes>(?:\s*[a-zA-Z_:!0-9,][-a-zA-Z0-9_:%."'`;(]*(?:\s*=\s*(?:(?:"[^"']*")|(?:'[^'"]*')|{{[^>}]*}}|[^>]+|\w*))?)*)\s*(\/?)>

尝试这个正则表达式,它将匹配整个属性,而不管引号。

wooyq4lh

wooyq4lh2#

正则表达式是错误的HTML解析工具。相反,使用DOM解析器--如DOMParser
请注意,您的输入字符串不是有效的HTML:属性值由第二个引号结束。该引号应在属性值的上下文中进行转义。由于您有多个单引号,因此最好用双引号将属性括起来,并对双引号进行转义。例如,输入可以是有效的,如下所示:

<span class="Utils.showtt(&quot;{{getI18n(zr.ratings.reviews.client.review.tag', getCrmModuleInfo('Accounts', 'true'))}}&quot;)">

使用DOMParser的示例:

const html = `<span class="Utils.showtt(&quot;{{getI18n(zr.ratings.reviews.client.review.tag', getCrmModuleInfo('Accounts', 'true'))}}&quot;)">`;

const elem = new DOMParser().parseFromString(html, "text/html")
                            .body.children[0];
console.log(elem.tagName); // SPAN
for (const attr of elem.attributes) {
    console.log(attr.name, "=", attr.value);
}

相关问题