how to grab and show multiple lines between two string(pattern) from a file in java

Tags:



i want to grab and show multi-lined string from a file (has more than 20,000 lines of text in it) between two desired string(pattern) using java

ex: file.txt(has more than 20,000 lines of text) pattern1 string that i want to grab pattern2

i want to grab and show text in between these two patterns(pattern1 and pattern2) which is in this case “string /n that i /n want /n to grab” how can i do that i tried Bufferreader ,file ,string and few more things but nothing worked

sorry im a noob

Answer

Is your pattern on several lines ?

One easy solution would be to store the content of you’r file and then check for you’r pattern with a regular expression :

      try {
         BufferedReader reader = new BufferedReader(new FileReader(new File("test.txt")));
         final StringBuilder contents = new StringBuilder();
         while(reader.ready()) {    // read the file content
             contents.append(reader.readLine());
         }   
         reader.close();
         Pattern p = Pattern.compile("PATTERN1(.+)PATTERN2"); // prepare your regex
         Matcher m = p.matcher(contents.toString());
         while(m.find()){ // for each
             String b =  m.group(1);
             System.out.println(b);
         }
      } catch(Exception e) {
         e.printStackTrace();
      }


Source: stackoverflow