Statement of Regular Expression

advertisements

I've never been good with regex and I can't seem to get this...

I am trying to match statements along these lines (these are two lines in a text file I'm reading)

Lname Fname 12.35 1
Jones Bananaman 7.1 3

Currently I am using this for a while statement

reader.hasNext("\\w+ \\w+ \\d*\\.\\d{1,2} [0-5]")

But it doesn't enter the while statement. The program reads the text file just fine when I remove the while. The code segment is this:

private void initializeFileData(){
    try {
        Scanner reader = new Scanner(openedPath);

        while(reader.hasNext("\\w+ \\w+ \\d*\\.\\d{1,2} [0-5]")){
            employeeInfo.add(new EmployeeFile(reader.next(), reader.next(), reader.nextDouble(), reader.nextInt(), new employeeRemove()));
        }
        for(EmployeeFile element: employeeInfo){
            output.add(element);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}


Use the \s character class for the spaces between words:

while(reader.hasNext("\\w+\\s\\w+\\s\\d*\\.\\d{1,2}\\s[0-5]"))

Update:

According to the javadoc for the Scanner class, by default it splits it's tokens using whitespace. You can change the delimiter it uses with the useDelimiter(String pattern) method of Scanner.

private void initializeFileData(){
    try {
        Scanner reader = new Scanner(openedPath).useDelimiter("\\n");
        ...
        while(reader.hasNext("\\w+\\s\\w+\\s\\d*\\.\\d{1,2}\\s[0-5]")){
        ...

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html