带包装短语的GREP(跨越多行的一个句子) - Java

时间:2018-01-24 21:07:44

标签: java grep

我正在试图弄清楚如何制作一个grep方法,可以在java中从最高到无限的行(这是一个跨越给定文本文件的多行的句子或字符串)中读取包装的短语。这是我目前的grep函数代码:

public static void grep() throws IOException{
    BufferedReader f = new BufferedReader(new FileReader("Cabbages.txt"));
    Scanner in = new Scanner(System.in);
    String line = "", input = "", wrappedPhrase = "", modified = "";
    int c = 0, foundCount = 0;
    boolean found = false;
    System.out.print("Please enter something you want to grep: ");
    input = in.nextLine();
    while((line = f.readLine()) != null) {
        c++;
        found = false;
        int index = line.indexOf(input);
        while(index >= 0) {
            modified = "<" + line.substring(line.indexOf(input), (line.indexOf(input)+input.length())) + ">";
            found = true;
            index = line.indexOf(input, index + 1);
            foundCount++;
        }
        if(found) {
            System.out.println("Found on line: " + c + ", which is: " + line.replace(input, modified));
        }
    }
    if(foundCount <= 0) {
        System.out.println("Sorry, the input string of: \"" + input + "\" was not found within the given file.");
    }else {
        System.out.println("In total, the input string of: \"" + input + "\"" + " was found " + foundCount + " time(s).");
    }
}

0 个答案:

没有答案