【发布时间】: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&fit=crop&w=70&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&fit=crop&w=70&h=70 70w\"/>";
Pattern pattern = Pattern.compile(IMG_PREFIX + "(.*?)" + IMG_SUFFIX);
Matcher matcher = pattern.matcher(line);
System.out.println(matcher.find());
}
}
编辑:生产代码使用这个HTML source 而不仅仅是一行。
【问题讨论】:
-
试试这个: (?
-
这适用于该特定行,但我正在抓取一个网页,它也使用 data-srcset 进行广告。
-
Parsing HTML with a regular expression is going to backfire on you. 请改用专用的 HTML 解析器。