1

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

4

3 回答 3

5

这是另一种选择:

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.

上面的片段打印

/courses/lorem/lecture-notes
/courses/ipsum/dolor/lecture-notes
于 2012-08-11T19:37:32.510 回答
1

假设您每行有 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
        }
    }
于 2012-08-11T19:42:32.943 回答
1

以下将返回中间部分(即:排除/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.
于 2012-08-11T19:48:49.893 回答