我试图理解这段代码的阵列提取特定字符串:JS从字符串
function extractLinks(input) {
var html = input.join('\n');
var regex = /<a\s+([^>]+\s+)?href\s*=\s*('([^']*)'|"([^"]*)|([^\s>]+))[^>]*>/g;
var match;
while (match = regex.exec(html)) {
var hrefValue = match[3];
if (hrefValue == undefined) {
var hrefValue = match[4];
}
if (hrefValue == undefined) {
var hrefValue = match[5];
}
console.log(hrefValue);
}
}
通过一切手段,这是一个简单的功能,即提取所有HREF值,但只有这些,这是真正的hrefs,例如不包括被定义为class="href"
的href,或者外部的A标签等。 这是奇怪的这一切,问题是,我该计算产生的regex
是 (<a[\s\S]*?>)
但是当我没能找到解决的办法,看着原来的一个,我发现这很长的regex
。 试过这个解决方案与我的regex
,它不会工作。
可以请,有人解释,我怎么解释这个长的regex
。 然后,匹配返回一个数组,然后。 让我看看,如果我得到这个while循环的理念:
而(匹配=正则表达式是存在的字符串){ 东西=匹配[3] /为什么3 ??? / 然后如果undefined something = match [4], if undefined something = match [5]; }
我真的很难理解其背后这一切的机制,以及在regex
逻辑。
该输入由系统生成,该系统将解析10个不同的字符串数组,但让我们用一个来测试: 下面的代码被解析为字符串数组,其长度与行,每行是数组中的单独元素,并且这是该函数的参数输入。
<!DOCTYPE html>
<html>
<head>
<title>Hyperlinks</title>
<link href="theme.css" rel="stylesheet" />
</head>
<body>
<ul><li><a href="/" id="home">Home</a></li><li><a
class="selected" href=/courses>Courses</a>
</li><li><a href =
'/forum' >Forum</a></li><li><a class="href"
onclick="go()" href= "#">Forum</a></li>
<li><a id="js" href =
"javascript:alert('hi yo')" class="new">click</a></li>
<li><a id='nakov' href =
http://www.nakov.com class='new'>nak</a></li></ul>
<a href="#empty"></a>
<a id="href">href='fake'<img src='http://abv.bg/i.gif'
alt='abv'/></a><a href="#"><a href='hello'></a>
<!-- This code is commented:
<a href="#commented">commentex hyperlink</a> -->
</body>
[**所有都是我所有的失去他的朋友来**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-标签) – adeneo 2014-11-14 23:25:26