【问题标题】:Regex to grab all ".js" and ".css" href links from file正则表达式从文件中获取所有“.js”和“.css”href 链接
【发布时间】:2015-10-09 14:47:42
【问题描述】:

我有一个包含 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());
}

【问题讨论】:

    标签: java html regex


    【解决方案1】:

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

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

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

    如果要搜索文字文本 catdog,请用竖线或竖线符号分隔两个选项:cat|dog。如果您需要更多选项,只需展开列表:cat|dog|mouse|fish

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 2012-01-08
      • 1970-01-01
      • 2023-03-28
      • 2016-12-14
      • 2014-03-22
      • 2013-08-28
      相关资源
      最近更新 更多