【发布时间】:2012-08-11 19:36:05
【问题描述】:
我有一个文本文档,其中有一堆/courses/......./.../.. 形式的网址
从这些网址中,我只想提取/courses/.../lecture-notes 形式的网址。表示以/courses 开头并以/lecture-notes 结尾的网址。
有人知道使用正则表达式或仅通过字符串匹配的好方法吗?
【问题讨论】:
标签: java regex text-parsing web-crawler
我有一个文本文档,其中有一堆/courses/......./.../.. 形式的网址
从这些网址中,我只想提取/courses/.../lecture-notes 形式的网址。表示以/courses 开头并以/lecture-notes 结尾的网址。
有人知道使用正则表达式或仅通过字符串匹配的好方法吗?
【问题讨论】:
标签: java regex text-parsing web-crawler
这是另一种选择:
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
【讨论】:
以下将仅返回中间部分(即:排除/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.
【讨论】:
假设您每行有 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
}
}
【讨论】:
^ 和 $ 在使用 matches 时不需要。)