0

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

raijin
  • 3
  • 2
  • Does this answer your question? [Match multiline text using regular expression](https://stackoverflow.com/questions/3651725/match-multiline-text-using-regular-expression) – Joakim Danielson Apr 29 '20 at 17:42

2 Answers2

0

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();
      }
Bapt.px
  • 16
  • 1
0

You can use this :

import java.util.regex.Pattern; import java.util.regex.Matcher;

public class HelloWorld{

public static void textBeetweenTwoPattern(String pattern1, String pattern2, String text){
    Pattern p = Pattern.compile(pattern1+"([^<]+)"+pattern2, Pattern.MULTILINE);
    Matcher m = p.matcher(text);
    while (m.find())
    {
        System.out.println(m.group(1)); 
    }  
}

 public static void main(String []args){
     textBeetweenTwoPattern("<b>", "</b>", "Test <b>regex</b> <i>Java</i> for \n\n<b>Stackoverflow</b> ");
 }

}

It returns : regex Stackoverflow

Ipromise
  • 27
  • 4