【问题标题】:Extracting specific urls from a text file using java使用java从文本文件中提取特定的url
【发布时间】:2012-08-11 19:36:05
【问题描述】:

我有一个文本文档,其中有一堆/courses/......./.../.. 形式的网址 从这些网址中,我只想提取/courses/.../lecture-notes 形式的网址。表示以/courses 开头并以/lecture-notes 结尾的网址。 有人知道使用正则表达式或仅通过字符串匹配的好方法吗?

【问题讨论】:

    标签: java regex text-parsing web-crawler


    【解决方案1】:

    这是另一种选择:

    Scanner s = new Scanner(new FileReader("filename.txt"));
    
    String str;
    while (null != (str = s.findWithinHorizon("/courses/\\S*/lecture-notes", 0)))
        System.out.println(str);
    

    给定一个filename.txt 的内容

    Here /courses/lorem/lecture-notes and
    here /courses/ipsum/dolor/lecture-notes perhaps.
    

    上面的sn-p打印

    /courses/lorem/lecture-notes
    /courses/ipsum/dolor/lecture-notes
    

    【讨论】:

      【解决方案2】:

      以下将返回中间部分(即:排除/courses//lectures-notes/

      Pattern p = Pattern.compile("/courses/(.*)/lectures-notes");
      Matcher m = p.matcher(yourStrnig);
      
      if(m.find()).
        return m.group(1) // The "1" here means it'll return the first part of the regex between parethesis.
      

      【讨论】:

        【解决方案3】:

        假设您每行有 1 个 URL,可以使用:

            BufferedReader br = new BufferedReader(new FileReader("urls.txt"));
            String urlLine;
            while ((urlLine = br.readLine()) != null) {
                if (urlLine.matches("/courses/.*/lecture-notes")) {
                    // use url
                }
            }
        

        【讨论】:

        • 描述中的 Nothing 排除了处理 url。此检查在循环中。
        • 除非您解释如何逐个令牌(或至少逐行)遍历文本令牌,否则此答案是不完整的。 (另外,^$ 在使用 matches 时不需要。)
        猜你喜欢
        • 2021-03-02
        • 2018-01-22
        • 1970-01-01
        • 2012-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        相关资源
        最近更新 更多