dongwuwan5646 2013-09-03 16:03
浏览 20
已采纳

基于工作的PHP代码在Java中使用Regex

I've been using this in php...

preg_match_all('|<a href="http://www.example.com/photoid/(.*?)"><img src="(.*?)" alt="(.*?)" /></a>|is',$xx, $matches, PREG_SET_ORDER);

where $xx is the entire webpage content as a string, to find all occurrences of matches.

This sets $matches to a two dimensional array which I can then loop through with a for statement based on the length of $matches and use for example ..

$matches[$i][1] which is would be the first (.*?)

$matches[$i][2] which is would be the second (.*?)

and so on....

My question is how can this be replicated in java? I've been reading tutorials and blogs on java regex and have been using Pattern and Matcher but can't seem to figure it out. Also, matcher never finds anything. so my while(matcher.find()) have been futile and usually throws an error saying no matches have been found yet

This is my java code for the pattern to be matched is ...

String pattern = new String(
    "<a href=\"http://www.example.com/photoid/(w+)\"><img src=\"(w+)\" alt=\"(w+)\" /></a>");

I've also tried ..

String pattern = new String(
    "<a href=\"http://www.example.com/photoid/(.*?)\"><img src=\"(.*?)\" alt=\"(.*?)\" /></a>");

and

String pattern = new String(
    "<a href=\"http://www.example.com/photoid/(\\w+)\"><img src=\"(\\w+)\" alt=\"(\\w+)\" /></a>");

no matches are ever found.

  • 写回答

2条回答 默认 最新

  • dongsaoshuo4326 2013-09-03 18:17
    关注

    The regex you posted worked for me so perhaps your fault is in how you use it :

    String test = "<html>
    <a href=\"http://www.mysite.com/photoid/potato.html\"><img src=\"quack-quack\" alt=\"hi\" /></a>
    </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
    

    See Java Tutorial on how this should be used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败