我想使用正则表达式获取嵌套在几个元素中的特定元素,而不使用 dom 解析器库和查询选择器方法。
正则表达式:
<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
来获取这些 h3
,
<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 会非常复杂。
Demo
<小时/>如果您想简化/修改/探索表达式,regex101.com 的右上角面板已对此进行了解释。 。如果您愿意,也可以在 this link 观看,它如何与一些示例输入相匹配。
<小时/>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}`);
});
}
关于javascript - 用于获取 javascript 中特定嵌套元素的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252084/