Cant find pattern with Scanner in Java 8

Tags: , , ,



I’m working with Java 8 on eclipse and trying to use regex to detect strings in a file, but I’m not detecting anything. I’ve tested the regex on its own and it successfully match’s strings in the file I’m searching. I’m successfully reading from the file because I’m able to print the entire thing. I’ve also tried simpler regex with the Pattern.compile(), like trying to match a single letter. But no matter the input it never detects anything.

Does anyone know what could be going on?

        File logText = new File("C:\\Users\\textFileLocation.txt");
        Scanner s;
        try {
            s = new Scanner(logText);
            Pattern p = Pattern.compile("\w+Exception:[^\n]+");
            System.out.println(s.hasNext(p));
            
            while(s.hasNextLine()){
                System.out.println(s.nextLine());
            }
            
            s.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
             

Here’s whats in the file:

2021-01-14 12:06:33,165 ERROR Server INTERNAL SERVER EXCEPTION #11: java.lang.IllegalStateException: Attempt to access bean of type “Address”

And here’s the output

false
2021-01-14 12:06:33,165 ERROR Server INTERNAL SERVER EXCEPTION #11:
java.lang.IllegalStateException: Attempt to access bean of type "Address"

Answer

You are not using the regex API correctly. You can use Matcher#find to check the match. Given below is the demo code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        File logText = new File("textFileLocation.txt");
        Pattern p = Pattern.compile("\w+Exception:[^\n]+");
        try (Scanner s = new Scanner(logText)) {
            while (s.hasNextLine()) {
                String str = s.nextLine();
                boolean found = p.matcher(str).find();
                System.out.println(found);
                if (found) {
                    System.out.println(str);
                }
            }
        }
    }
}

Output:

true
2021-01-14 12:06:33,165 ERROR Server INTERNAL SERVER EXCEPTION #11: java.lang.IllegalStateException: Attempt to access bean of type "Address"

Learn more about Java regex API from Lesson: Regular Expressions.

Also, I recommend you use try-with-resources to close the resource automatically.



Source: stackoverflow