我有一个包含 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
ordog
, 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/