Javascript 函数的作用是:返回完全匹配的标记
它将返回整个标记:Javascript 函数的作用是:返回完全匹配的标记,javascript,regex,parsing,screen-scraping,Javascript,Regex,Parsing,Screen Scraping,它将返回整个标记: http://google, http://yahoo.com , 为什么会这样 您需要RegExp#exec和一个循环,在匹配结果的1索引处访问元素,而不是String.matchString.match在有g标志时不返回捕获组,只返回每个匹配的索引0处的元素数组,这是整个匹配字符串。(见第15.5.4.10节。) 因此,本质上: <a href="http://google.com">Google.com</a>, <a href="ht
http://google, http://yahoo.com
,
为什么会这样 您需要RegExp#exec
和一个循环,在匹配结果的1
索引处访问元素,而不是String.match
String.match
在有g
标志时不返回捕获组,只返回每个匹配的索引0
处的元素数组,这是整个匹配字符串。(见第15.5.4.10节。)
因此,本质上:
<a href="http://google.com">Google.com</a>, <a href="http://yahoo.com">Yahoo.com</a>
这并不是说你的regexp有问题,只是要强调正则表达式本身不能可靠地用于解析HTML。它们可以构成解决方案的一部分,帮助您扫描令牌,但它们不能可靠地完成整个工作。虽然确实无法使用正则表达式可靠地解析HTML,但OP并不是这样要求的 相反,OP需要一种从HTML文档中提取锚链接的方法,该文档可以使用正则表达式轻松地处理 在前一个响应者列出的四个问题中:
double-quote test
single-quote test
leading prop test
trailing prop test
multiple prop test
inline newline test
但这确实不必要,因为RegExp.exec()在失败时返回“null”。另外,请注意,正确的匹配类型是“对象”,而不是“数组”因为您正在使用正则表达式来解析html。这也是因为第一个数组项始终包含整个匹配项,随后它会包含括号中的匹配项。@Zirak:这是整个响应,但在括号中。我理解不使用正则表达式解析html标记的原因,但这是在nodejs上,所以我没有任何选项。尝试过jsdom和apricot,但错误百出,尚未成熟。“但这是在nodejs上,所以我没有任何选择”你有。:-)您可以创建自己的解析逻辑(可能使用一些针对位和段的正则表达式),对于这样的简单提取,它可以更加智能。+1用于查找错误、修复错误并详细说明我的正则表达式的所有错误。我也读了你对上述问题的评论。这些链接是我在这个应用程序中所需要的全部,所以我认为只要我巩固我的正则表达式以覆盖所有不同的链接,比如你提到的lackings,我就可以了。编写自己的解析逻辑实际上是在试图重新发明轮子,特别是对于这样简单的东西。我很有信心jsdom和其他解析器会很快成熟。
var re, match, html;
re = /<a href="(.*?)">[^<]+<\/a>/g;
html = 'Testing <a href="http://yahoo.com">one two three</a> <a href="http://google.com">one two three</a> foo';
re.lastIndex = 0; // Work around literal bug in some implementations
for (match = re.exec(html); match; match = re.exec()) {
display(match[1]);
}
<a href="http://google.com" class="foo">
< # a literal '<'
a # a literal 'a'
[^>]+? # one or more chars which are not '>' (non-greedy)
href= # literal 'href='
('|") # either a single or double-quote captured into group #1
([^\1]+?) # one or more chars that are not the group #1, captured into group #2
\1 # whatever capture group #1 matched
<a[^>]+?href=('|")([^\1]+?)\1
var source='<a href="double-quote test">\n'+
'<a href=\'single-quote test\'>\n'+
'<a class="foo" href="leading prop test">\n'+
'<a href="trailing prop test" class="foo">\n'+
'<a style="bar" link="baz" '+
'name="quux" '+
'href="multiple prop test" class="foo">\n'+
'<a class="foo"\n href="inline newline test"\n style="bar"\n />';
<a href="double-quote test">
<a href='single-quote test'>
<a class="foo" href="leading prop test">
<a href="trailing prop test" class="foo">
<a style="bar" link="baz" name="quux" href="multiple prop test" class="foo">
<a class="foo"
href="inline newline test"
style="bar"
/>
var RE=new RegExp(/<a[^>]+?href=('|")([^\1]+?)\1/gi),
match;
while(match=RE.exec(source)) {
console.log(match[2]);
}
double-quote test
single-quote test
leading prop test
trailing prop test
multiple prop test
inline newline test
if(match && typeof match === 'object' && match.length > 1) {
console.log(match[2]);
}