java - 正则表达式从文件中获取所有 ".js"和 ".css"href 链接

标签 java html regex

我有一个包含 HTML 内容的字符串,我需要获取 .css.js 文件的所有链接。现在,我使用此模式 "(http:.*?.\\.css)" 来获取所有 CSS 链接,但如何也包含 .js 链接?

这是我的完整代码:

List<String> urlList =  new ArrayList<String>();
String str = new String(Files.readAllBytes(FileSystems.getDefault().getPath("c:" + File.separator + "nutchfiles" + File.separator + "test.html")));
Pattern p = Pattern.compile("(http:.*?.\\.css)");
Matcher m = p.matcher(str);

while (m.find()) {
    LOG.info("matched urls" + m.group());
}

最佳答案

如果您正在寻找正则表达式修复,这里是:

Pattern p = Pattern.compile("(http:.*?\\.(?:css|js)\\b)");

交替将帮助您匹配两个扩展名。请参阅Alternation with The Vertical Bar or Pipe Symbol :

If you want to search for the literal text cat or dog, separate both options with a vertical bar or pipe symbol: cat|dog. If you want more options, simply expand the list: cat|dog|mouse|fish.

但是,使用 HTML 解析器从 HTML 文件中获取任何内容会更安全。

关于java - 正则表达式从文件中获取所有 ".js"和 ".css"href 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517187/

相关文章:

java - 我正在尝试在我的游戏屏幕(用户玩游戏的地方)上创建一个暂停屏幕

javascript - Amature javascript 引用文本文件

html - 表单控件中的 Bootstrap 输入文本占用了一些不需要的边距

regex - 如何将 "backspace character"添加到 vscode 中的正则表达式输出更改?

java - 创建一个类来扩展 API

Java- Jersey ,JAX RS

Java 正则表达式 X{n,m} X,至少 n 但不超过 m 次

regex - fnr.exe 正则表达式捕获组输出

java - 在java中计算百分比

html - 是否可以像 div 一样将文本环绕在 block 元素周围,就像图像一样