有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正则表达式如何在字符首次出现时停止

我试图从标记中提取src值, 到目前为止,我似乎能够提取src值和字符串中最后一个引号之间的字符串

字符串:

<img  border="0"  src="http://i.bookfinder.com/about/booksellers/logo_borderless/amazon_uk.gif" width="89" height="31" alt="">

例如在PHP中:

preg_match('/src=\"(.*)\"/', $row->find('a img',0), $matches);
if($matches){
   echo $matches[0];
}

打印出来 src="http://i.bookfinder.com/about/booksellers/logo_borderless/amazon_uk.gif" width="89" height="31" alt=""

但我真正想要的是 src="http://i.bookfinder.com/about/booksellers/logo_borderless/amazon_uk.gif"

或者如果可能的话 http://i.bookfinder.com/about/booksellers/logo_borderless/amazon_uk.gif

我应该在正则表达式中添加什么?谢谢


共 (2) 个答案

  1. # 1 楼答案

    试试看,它应该适合你的需要

    /src=\"[^\"]+\"/
    
  2. # 2 楼答案

    你实际上非常接近>>

    Yours:        preg_match('/src=\"(.*)\"/',  $row->find('a img',0), $matches);
    Correct one:  preg_match('/src=\"(.*?)\"/', $row->find('a img',0), $matches);
    

    通过添加?可以请求match .*lazy,这意味着它将在需要时匹配任何内容,而不是在can之前匹配任何内容。如果没有lazy操作符,它将停在最后一个双引号"前面,它位于alt="后面