【问题标题】:Regex not extracting image url from html tag [duplicate]正则表达式未从 html 标签中提取图像 url [重复]
【发布时间】:2018-08-01 20:35:16
【问题描述】:

我的正则表达式是

<source media="(min-width: 0px)" sizes="70px" data-srcset="(.*?)"/>

我用来测试正则表达式的文本是

<source media="(min-width: 0px)" sizes="70px" data-srcset="https://static2.therichestimages.com/wordpress/wp-content/uploads/2014/05/52f81afc8b39c.jpg?q=50&amp;fit=crop&amp;w=70&amp;h=70 70w"/>

它没有检测到 data-srcset 属性中的 URL。

我的代码是

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {

    private static final String IMG_PREFIX =
            "<source media=\"(min-width: 0px)\" sizes=\"70px\" data-srcset=\"";
    private static final String IMG_SUFFIX = "\"/>";

    public static void main(String[] args) {
        String line = "<source media=\"(min-width: 0px)\" sizes=\"70px\" data-srcset=\"https://static1.therichestimages.com/wordpress/wp-content/uploads/2012/06/Michael-Bloomberg.jpg?q=50&amp;fit=crop&amp;w=70&amp;h=70 70w\"/>";

        Pattern pattern = Pattern.compile(IMG_PREFIX + "(.*?)" + IMG_SUFFIX);
        Matcher matcher = pattern.matcher(line);

        System.out.println(matcher.find());

    }
}

编辑:生产代码使用这个HTML source 而不仅仅是一行。

【问题讨论】:

标签: java regex matcher


【解决方案1】:

编辑

将您的模式更改为:

String regex = "<source media=\"\\(min-width: 0px\\)\" sizes=\"70px\" data-srcset=\"(.+)\"/>";

Pattern pattern = Pattern.compile(regex);

问题是您的当前正则表达式将括号作为“文本”的一部分,但它们没有正确转义,因为它们是正则表达式运算符。

具体

(min-width: 0px)

应该是:

\(min-width: 0px\)

在 Java 领域,因为你必须转义一个反斜杠:

\\(min-width: 0px\\)

例子:

public static void main(String[] args) {
    String line = "<source media=\"(min-width: 0px)\" sizes=\"70px\" data-srcset=\"https://static1.therichestimages.com/wordpress/wp-content/uploads/2012/06/Michael-Bloomberg.jpg?q=50&amp;fit=crop&amp;w=70&amp;h=70 70w\"/>\n";
    String regex = "<source media=\"\\(min-width: 0px\\)\" sizes=\"70px\" data-srcset=\"(.+)\"/>";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(line);
    while(matcher.find()) {
        System.out.println(matcher.group(1));
    }
}

我得到的输出:

https://static1.therichestimages.com/wordpress/wp-content/uploads/2012/06/Michael-Bloomberg.jpg?q=50&amp;fit=crop&amp;w=70&amp;h=70 70w

【讨论】:

  • 我使用前缀和后缀的原因是因为我正在抓取一个网页,它有显示带有 data-srcset 属性的广告图片。
  • 例如static0.therichestimages.com/wordpress/wp-content/uploads/2018/…487w"/>
  • 但我不希望我的代码与之匹配
  • 我明白了,这不仅仅是您要搜索的唯一文本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2014-06-16
  • 2015-10-02
相关资源
最近更新 更多