我想使用regex而不使用dom解析器库和queryselector方法将特定元素嵌套在几个元素中。
正则表达式:
<art .*?id="src".*?>(?:\s+)?<section .*?class="product".*?>(?:\s+)?<h3>(?:\s+)?(.+?)(?:\s+)?<\/h3><\/section>(?:\s+)?<\/art>
内容:
<art id="src">
<section class="product">
<h3>xvd</h3>
<p>
sjfdsjvdvds
</p>
</section>
<section class="product">
<h3>avdsvd</h3>
<p>
djsfdsjgdjs
</p>
</section>
<section class="product">
<h3>zdvdsv</h3>
<p>
safdgdsghhrh
</p>
</section>
<section class="product">
<h3>dd</h3>
<p>zscsvdsvdsv</p>
</section>
</art>
请帮助我纠正正则表达式
我的猜测是您可能会h3
textContent
使用,
<section .*?class="product".*?>\s*<h3>\s*(.+?)\s*<\/h3>.*?<\/section>\s*
那么如果您需要检查art
元素,也许用进行更改,
<section .*?class="product".*?>\s*<h3>\s*(.+?)\s*<\/h3>.*?<\/section>\s*|<art .*?id="src".*?>
将是一个选项,否则使用JavaScript将会非常复杂。
如果您想简化/修改/探索表达式,请在regex101.com的右上方面板中进行说明。如果您愿意,您还可以在此链接中观看,它如何与一些示例输入匹配。
const regex = /<section .*?class="product".*?>\s*<h3>\s*(.+?)\s*<\/h3>.*?<\/section>\s*|<art .*?id="src".*?>/gs;
const str = `<art id="src">
<section class="product">
<h3>xvd</h3>
<p>
sjfdsjvdvds
</p>
</section>
<section class="product">
<h3>avdsvd</h3>
<p>
djsfdsjgdjs
</p>
</section>
<section class="product">
<h3>zdvdsv</h3>
<p>
safdgdsghhrh
</p>
</section>
<section class="product">
<h3>dd</h3>
<p>zscsvdsvdsv</p>
</section>
</art>`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句