2014-11-14 59 views
-1

我试图理解这段代码的阵列提取特定字符串: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="#">&lt;a href='hello'&gt;</a> 
<!-- This code is commented: 
    <a href="#commented">commentex hyperlink</a> --> 
</body> 
+5

[**所有都是我所有的失去他的朋友来**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-标签) – adeneo 2014-11-14 23:25:26

回答

1

获取这正则表达式是做一个了解,我已经把在线评论中this page,你可以查看。我也在这里复制它:

<a\s+   # Look for '<a' followed by whitespace 
([^>]+\s+)?  # Look for anything else that isn't 'href=' 
       # such as 'class=' or 'id=' 
href\s*=\s*  # locate the 'href=' with any whitespace around the '=' character 
(
    '([^']*)'  # Look for '...' 
|    # ...or... 
    "([^"]*)  # Look for "..." 
|    # ...or... 
    ([^\s>]+)  # Look anything NOT '>' or spaces 
) 
[^>]*>   # Match anything else up to the closing '>' 

这只是打破它分开,所以你可以看到每个部分正在做什么。至于你对match的问题,我不完全理解你的问题。

+0

好吧,谢谢你的正则表达式,看看。 而'while while循环的部分是,为什么我们需要数组匹配的第三个元素,如果它是未定义的,我们会选择第四个,然后是第五个。 – Sineastra 2014-11-14 23:41:16

+0

我认为这里发生的事情是,有些“被捕获”的URL部分不需要保留。 [这一个](http://regex101.com/r/qQ3nA9/3)有一些变化,它只捕获'href ='部分。在这种情况下,您可以在该页面的底部看到更换。 – OnlineCop 2014-11-14 23:49:50

+0

您先生,请感谢您。 – Sineastra 2014-11-14 23:54:36