我的正则表达式是
<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 而不仅仅是一行。
最佳答案
编辑
将您的模式更改为:
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&fit=crop&w=70&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&fit=crop&w=70&h=70 70w
关于java - 正则表达式不从 html 标签中提取图像 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641883/