我正在这样做:
List<String> listOfLinks = new ArrayList<String>();
String regex = startMatch + "(.*)" + endMatch;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
listOfLinks.add(matcher.group(1));
}
其中正则表达式的值为:
class="thumb-link" href="(.*)" titl
我得到这个结果:
http://www.sportscraft.com.au/longline-vest--9344961510736.html" title="Longline Vest "> <img class="alpha" src="http://demandware.edgesuite.net/sits_pod19/dw/image/v2/AAJZ_PRD/on/demandware.static/Sites-Sportscraft-Site/Sites-sc-master/default/v1427554286311/images/hi-res/1102031_black_a.jpg?sw=180&sh=215&sm=fit" alt="Longline Vest , BLACK, hi-res" title="Longline Vest , BLACK" height="214" /> <img class="beta" src="http://demandware.edgesuite.net/sits_pod19/dw/image/v2/AAJZ_PRD/on/demandware.static/Sites-Sportscraft-Site/Sites-sc-master/default/v1427554286311/images/hi-res/1102031_black_b.jpg?sw=180&sh=215&sm=fit" alt="Longline Vest , BLACK, hi-res
当我想要的是:
http://www.sportscraft.com.au/longline-vest--9344961510736.html
这意味着,正则表达式 class="thumb-link"
的第一部分工作正常。但是第二部分"title
在第一次匹配时并没有停止。它会继续下去,直到找到另一个匹配项。
当我在 http://myregexp.com/ 上测试时使用相同的正则表达式我得到了正确的结果。我想我需要设置一些选项来使这个“非贪婪”,但不确定是哪个,因为我无法在正则表达式测试器中重现错误。
最佳答案
尝试使用类似的东西:
String regex = "^(.*?[^ ]) .*?";//remove ^, i have tried on your input string.
Output:
[http://www.sportscraft.com.au/longline-vest--9344961510736.html"]
关于java - 正则表达式匹配超出应有的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325990/