如何使用正则表达式不匹配其中包含某些标签的HTML标签? [英] How to use regexp to not match HTML tags that have certain tags inside them?
本文介绍了如何使用正则表达式不匹配其中包含某些标签的HTML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的链接,我想与regexp匹配:
I have a link like this that I want to match with regexp:
<a href="tel:something">something</a>
我设法将其与< a [^>] + tel:.*?>.*?< \/a>
但是我不想匹配其中嵌套了< span></span>
的链接:
But I don't want to match links that have <span></span>
nested inside them:
<a href="tel:[some_numbers]"><span class="hello">Hello</span>[some_numbers]</a>
我尝试使用否定的超前(?!(< \/?span [^>] *>))
来排除< span></span>
,但是没有用.我的正则表达式如下:
I tried to use negative lookahead (?!(<\/?span[^>]*>))
to exclude <span></span>
but it didn't work. My regex below:
/<a[^>]+tel:.*?>(?!(<\/?span[^>]*>)).*?<\/a>/ig
推荐答案
您应该使用XPath:
You should do this with XPath:
// Our HTML source
var s = `<a href="tel:something">something1</a>
<a href="tel:[some_numbers]"><span class="hello">Hello1</span>[some_numbers]</a>
<a href="tel:something">something2</a>
<a href="tel:[some_numbers]"><span class="hello">Hello2</span>[some_numbers]</a>
<a href="tel:something">something3</a>
<a href="tel:[some_numbers]"><span class="hello">Hello3</span>[some_numbers]</a>`;
// Create a root div because XML requires a single root element
var div = document.createElement('div');
// Set the innerHTML to our string
div.innerHTML = s;
// Find <a> tags with no direct child <span> tag(s)
var iterator = document.evaluate('//a[not(span)]', div, null, XPathResult.ANY_TYPE, null);
// Set the iterator
var thisNode = iterator.iterateNext();
// Loop the iterator and log the node found
while (thisNode) {
console.log(thisNode);
thisNode = iterator.iterateNext();
}
https://jsfiddle.net/kad3ouqL/
这应该产生:
<a href="tel:something">something1</a>
<a href="tel:something">something2</a>
<a href="tel:something">something3</a>
这篇关于如何使用正则表达式不匹配其中包含某些标签的HTML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文