Search code examples
javaregexextract

Java regex extract specific values in long log


I have a very long text and I'm extracting some specific values that are followed by some particular words. Here's an example of my long text:

.........
FPS(FramesPerSecond)[ValMin: 29.0000, ValMax: 35.000]
.........
TotalFrames[ValMin: 100000, ValMax:200000]
.........
MemoryUsage(In MB)[ValMin:190000MB, ValMax:360000MB]
.........

here's my code:

File file = filePath.toFile();
        JSONObject jsonObject = new JSONObject();
String FPSMin="";
String FPSMax="";
String TotalFramesMin="";
String TotalFramesMax="";
String MemUsageMin="";
String MemUsageMax="";

String log = "my//log//file";

        final Matcher matcher = Pattern.compile("FPS/\(FramesPerSecond/\)/\[ValMin:");
        if(matcher.find()){
            FPSMin= matcher.end().trim();
        }

But I can't make it work. Where am I wrong? Basically I need to select, for each String, the corresponding values (max and min) coming from that long text and store them into the variables. Like

FPSMin = 29.0000
FPSMax = 35.0000
FramesMin = 100000
Etc 

Thank you

EDIT: I tried the following code (in a test case) to see if the solution could work, but I'm experiencing issues because I can't print anything except an object. Here's the code:

 @Test
    public void whenReadLargeFileJava7_thenCorrect()
            throws IOException, URISyntaxException {
        Scanner txtScan = new Scanner("path//to//file//test.txt");


        String[] FPSMin= new String[0];
        String FPSMax= "";
  
//Read File Line By Line
        while (txtScan.hasNextLine())   {
            // Print the content on the console
            String str = txtScan.nextLine();
            Pattern FPSMin= Pattern.compile("^FPS\\(FramesPerSecond\\)\\[ValMin:");
            Matcher matcher = FPSMin.matcher(str);

            if(matcher.find()){
                String MinMaxFPS= str.substring(matcher.end(), str.length()-1);
                String[] splitted = MinMaxFPS.split(",");
                FPSMin= splitted[0].split(": ");
                FPSMax = splitted[1];

            }

            System.out.println(FPSMin);
            System.out.println(FPSMax);

        }

Solution

  • Maybe your pattern should be like this ^FPS\\(FramesPerSecond\\)\\[ValMin: . I've tried it and it works for me.

        String line = "FPS(FramesPerSecond)[ValMin: 29.0000, ValMax: 35.000]";
        
        Pattern pattern = Pattern.compile("^FPS\\(FramesPerSecond\\)\\[ValMin:");
        
        Matcher matcher = pattern.matcher(line);
        
        if (matcher.find()) {
            
            System.out.println(line.substring(matcher.end(), line.length()-1));
            
        }
    }
    

    In that way, you get the offset of the line that you want to extract data and using the substring function you can get all characters starting from offset until the size of the line-1 (because you dont want to get also the ] character)