【发布时间】:2018-04-06 05:31:34
【问题描述】:
我需要有关 java 代码的帮助来读取一个日志文件,该文件可以打印所有以 START 字结尾的行。
我的文件包含:
test 1 START
test2 XYZ
test 3 ABC
test 2 START
应该打印出来
test 1 START
test 2 START
我尝试了下面的代码,但它只打印 START。
public class Findlog{
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new FileReader("myfile"));
Pattern patt = Pattern.compile(".*START$");
// For each line of input, try matching in it.
String line;
while ((line = r.readLine()) != null) {
// For each match in the line, extract and print it.
Matcher m = patt.matcher(line);
while (m.find()) {
// Simplest method:
// System.out.println(m.group(0));
// Get the starting position of the text
System.out.println(line.substring(line));
}
}
【问题讨论】:
-
String 有一个名为
endsWith的方法。为什么不使用它而不是正则表达式?除此之外,您当前的问题很简单,不是打印您在其中读取的line,而是打印您的正则表达式匹配的行的一部分,即“START”。 -
非常感谢 OH GOD SPIDERS ,我使用了 line 并删除了子字符串,它按预期工作。