我正在尝试从这样的HTML字符串中获取第一个图像:
每个图像都有这种类型的URL:
这就是我一直尝试做的事情,但没有成功,我不明白为什么会发生这种情况。
...
<table border="0" cellpadding="2" cellspacing="7" style="vertical-align:top;"><tr><td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=us&usg=AFQjCNFfn6RXQ3v898sGY_-sFLGCJ4EV5Q&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52778551504048&ei=zfK5U7D4JoLi1Ab0wIHwDw&url=http://online.wsj.com/articles/obamas-letters-to-corinthian-1404684555"><img src="//t3.gstatic.com/images?q=tbn:ANd9GcQVyQsQJvKMgXHEX9riJuZKWav5U1nI-jdB-i1HwFYQ-7jGvGrbk9N_k0XEDMVH-HAbLxP1wrU" alt="" border="1" width="80" height="80" /><br /><font size="-2">Wall Street Journal</font></a></font></td><td valign="top" class="j"><font style="font-size:85%;font-family:arial,sans-serif"><br /><div style="padding-top:0.8em;"><img alt="" height="1" width="1" /></div><div class="lh"><a href="http://news.google.com/news/url?sa=t&fd=R&ct2=us&usg=AFQjCNFfn6RXQ3v898sGY_-sFLGCJ4EV5Q&clid=c3a7d30bb8a4878e06b80cf16b898331&cid=52778551504048&ei=zfK5U7D4JoLi1Ab0wIHwDw&url=http://online.wsj.com/articles/obamas-letters-to-corinthian-1404684555"><b><b>Obama's</b> Letters to Corinthian</b></a><br /><font size="-1"><b><font color="#6f6f6f">Wall Street Journal</font></b></font><br /><font size="-1">The <b>Obama</b> Administration has targeted for-profit colleges as if they are enemy combatants. And now it has succeeded in putting out of business Santa Ana-based Corinthian Colleges for a dilatory response to document requests. Does the White House plan ...</font><br /><font size="-1" class="p"></font><br /><font class="p" size="-1"><a class="p" href="http://news.google.com/news/more?ncl=dPkBozywrsIXKoM&authuser=0&ned=us"><nobr><b>and more »</b></nobr></a></font></div></font></td></tr></table>
这是图片的标签
<img src="//t3.gstatic.com/images?q=tbn:ANd9GcQVyQsQJvKMgXHEX9riJuZKWav5U1nI-jdB-i1HwFYQ-7jGvGrbk9N_k0XEDMVH-HAbLxP1wrU" alt="" border="1" width="80" height="80">
每个图像都有这种类型的URL:
//tx.gstatic.com
,其中x是一个数字,我认为在0<x<3之间。这就是我一直尝试做的事情,但没有成功,我不明白为什么会发生这种情况。
var re = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var results = re.exec(HTMLSTRING);
var img="";
if(results!=null && results.length!=0) img = results[0];
\>
,但是在src
值的末尾之后,您只允许空格字符。看起来您实际上并不需要一直匹配到\>
的结尾。 - cookie monsterresults
不是null
,那么它的.length
将不为0
,虽然如果你想要src
值,则似乎需要索引[1]
。此外,你的方法取决于属性的顺序、标签名称的小写以及使用双引号而不是单引号。只是想指出这一点。 - cookie monster