正则表达式进入 html 属性匹配的无限循环

问题描述 投票:0回答:2
<(?<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'))}}")'>

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

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

试试这个正则表达式,它会匹配整个属性,而不考虑引号。


0
投票

Regex 是解析 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);
}

© www.soinside.com 2019 - 2024. All rights reserved.