我一直在php中使用它。。。
preg_match_all('|<a href="http://www.example.com/photoid/(.*?)"><img src="(.*?)" alt="(.*?)" /></a>|is',$xx, $matches, PREG_SET_ORDER);
其中$xx是作为字符串的整个网页内容,以查找所有匹配项。
这将$matches设置为二维数组,然后我可以根据$matchess的长度使用for语句循环遍历该数组,并使用例如。。
$matches[$i][1]
,它将是第一个(.*?)
$matches[$i][2]
,其将是第二个(.*?)
等等…
我的问题是如何在java中复制这一点?我一直在阅读关于java regex的教程和博客,并一直在使用Pattern和Matcher,但似乎无法理解。而且,matcher从来没有找到任何东西。所以我的while(matcher.find())
是徒劳的,通常会抛出一个错误,说还没有找到匹配的
这是我的java代码,用于匹配的模式是。。。
String pattern = new String(
"<a href='"http://www.example.com/photoid/(w+)'"><img src='"(w+)'" alt='"(w+)'" /></a>");
我也试过。。
String pattern = new String(
"<a href='"http://www.example.com/photoid/(.*?)'"><img src='"(.*?)'" alt='"(.*?)'" /></a>");
和
String pattern = new String(
"<a href='"http://www.example.com/photoid/(''w+)'"><img src='"(''w+)'" alt='"(''w+)'" /></a>");
没有找到匹配项。
您发布的正则表达式对我有效,所以您的错误可能在于如何使用它:
String test = "<html>'n<a href='"http://www.mysite.com/photoid/potato.html'"><img src='"quack-quack'" alt='"hi'" /></a>'n</html>";
// This is exactly the pattern code you posted :
String pattern = new String(
"<a href='"http://www.mysite.com/photoid/(.*?)'"><img src='"(.*?)'" alt='"(.*?)'" /></a>");
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(test);
m.find(); // returns true
请参阅Java教程了解如何使用它。
不是Java专家,但字符串不应该转义双引号和转义吗?
"<a href='"http://www.mysite.com/photoid/(.*?)'"><img src='"(.*?)'" alt='"(.*?)'" /></a>"
or
"<a'' href='"http://www.mysite.com/photoid/(.*?)'"><img'' src='"(.*?)'"'' alt='"(.*?)'"'' /></a>"