Java - Groovy: regex parser text block

I know this is a general question, and I went through a lot of forums to find out what the problem is in my code.

I need to read a text file with several blocks in the following format:

import com.myCompanyExample.gui.Layout

/*some comments here*/

@Layout
LayoutModel currentState() {
   MyBuilder builder = new MyBuilder()
   form example
     title form{
        row_1
        row_1 
        row_n
      }
   return build.get()
}

@Layout
LayoutModel otherState() {
   ....
   ....
   return build.get()
}

I have this code to read the entire file, and I would like to extract each block between the keyword "@Layout" and the keyword "return". I also need to catch the whole new line, so later I can split each matching block into a list

private void myReadFile(File fileLayout){
    String line = null;
    StringBuilder allText = new StringBuilder();
    try{
        FileReader fileReader = new FileReader(fileLayout);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        while((line = bufferedReader.readLine()) != null) {
            allText.append(line)
        }
        bufferedReader.close();
    }
    catch(FileNotFoundException ex) {
        System.out.println("Unable to open file");
    }
    catch(IOException ex) {
        System.out.println("Error reading file");
    }
    Pattern pattern = Pattern.compile("(?s)@Layout.*?return",Pattern.DOTALL);
    Matcher matcher = pattern.matcher(allText);
    while(matcher.find()){
       String [] layoutBlock = (matcher.group()).split("\\r?\\n")
      for(index in layoutBlock){
           //check each line of the current block
      }
}

layoutBlock returns size = 1

+4
source share
1 answer

, XY ... groovy @Layout , , (view -).

loc :

Pattern pattern = Pattern.compile( "@Layout(?:(?!@Layout).)*", Pattern.DOTALL );

PS: (?s) , Pattern.DOTALL ( ), .

UPDATE

, ( ) , (bufferedReader.readline() ).

allText:

String ln = System.lineSeparator();
while((line = bufferedReader.readLine()) != null) {
    allText.append(line + ln);
}

, :

import java.nio.file.Files;
import java.nio.file.Paths;

//can throw an IOException
String filePath = "/path/to/layout.groovy";
String allText = new String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);
+1

Source: https://habr.com/ru/post/1619719/


All Articles