使用Java获取CSS文件中图像的URL?

发布于 2024-12-17 07:37:00 字数 572 浏览 2 评论 0原文

我正在尝试使用 Java 获取远程 CSS 文件中图像(所有 MIME 类型)的 URL。

我正在使用 jsoup 来获取 css 的 URL。

经过无数个小时的研究 CSS Parser 由于缺乏文档,我无法弄清楚。

我还查看了其他一些步骤,但让我更加困惑:

我也见过一些使用正则表达式的示例,但我不太熟悉如何在java中实现它。

有人对如何解决这个问题有一些建议吗?

I'm trying to get the URLs for images (all MIME types) in a remote CSS file using Java.

I am using jsoup to get the URL of the css.

After countless hours of looking at CSS Parser I couldn't figure it out due to the lack of documentation.

I also looked at some other treads, but have just confused me even more:

I've also seen some examples using regex, but I am not too familiar how to implement it in java.

Would anyone have some suggestions on how to go at this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笔芯 2024-12-24 07:37:00

在 Java 中,您必须使用 java.util.regex 包。

您编译模式,然后用字符串实例化匹配器,然后查找与模式匹配的所有内容。

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 规范指出:

URI 值的格式为 'url(' 后跟可选的空格,后跟可选的单引号 (') 或双引号 (") 字符,后跟 URI 本身,后跟可选的单引号 (')或双引号 (") 字符,后跟可选的空格,后跟 ')'。两个引号字符必须相同。

因此,您可以使用像这样的正则表达式:

url\(\s*(['"]?+)(.*?)\1\s*\)

.*? 是非贪婪的,允许您根据需要使用尽可能少的字符。所有格量词避免了 ['"]?+ 中的任何回溯。

In Java, you have to use a Pattern and a Matcher from the java.util.regex package.

You compile your pattern, then you instantiate your matcher with your string and then you look for everything that matches your pattern.

Pattern p = Pattern.compile("...");
Matcher m = p.matcher("your CSS file as a String");
while (m.find()) {
  // Here use m.group(), m.group(1), ...
}

The CSS 2.1 spec states:

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.

Thus you could use a regex like this one:

url\(\s*(['"]?+)(.*?)\1\s*\)

The .*? is non-greedy allowing you to take as few characters as necessary. The possessive quantifier avoids any backtrack in ['"]?+.

谁把谁当真 2024-12-24 07:37:00

您也可以使用 ph-css 来实现此目的。
请参阅位于 https://github.com 的示例“访问 CSS 中包含的所有 URL” /phax/ph-css#code-examples
再简单不过了:)

You may also use ph-css for this.
See the example "Visit all URLs contained in a CSS" located at https://github.com/phax/ph-css#code-examples.
Can't do it much easier :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文