我正在尝试使用 Java 获取远程 CSS 文件中图像(所有 MIME 类型)的 URL。
我正在使用 jsoup 获取 css 的 URL。
经过无数小时的查看CSS Parser由于缺少文档,我无法弄清楚。
我还看了一些其他的胎面,但让我更加困惑:
我也看过一些使用正则表达式的例子,但我不太熟悉如何在 java 中实现它。
谁能对如何解决这个问题提出一些建议?
最佳答案
在 Java 中,您必须使用 java.util.regex
中的 Pattern
和 Matcher
包。
你编译你的模式,然后用你的字符串实例化你的匹配器,然后你寻找与你的模式匹配的所有东西。
Pattern p = Pattern.compile("...");
Matcher m = p.matcher("your CSS file as a String");
while (m.find()) {
// Here use m.group(), m.group(1), ...
}
CSS 2.1 规范指出:
The format of a URI value is 'url(' followed by optional white space followed by an optional single quote (') or double quote (") character followed by the URI itself, followed by an optional single quote (') or double quote (") character followed by optional white space followed by ')'. The two quote characters must be the same.
因此您可以使用像这样的正则表达式:
url\(\s*(['"]?+)(.*?)\1\s*\)
.*?
是非贪婪的,允许您根据需要使用尽可能少的字符。所有格量词避免了 ['"]?+
中的任何回溯。
关于java - 使用 Java 获取 CSS 文件中图像的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8207907/