Scanning a file for a pattern

92 views Asked by At

I'm currently working on a simple parsing program which reads certain patterns out of a file, formats them and then write them into an output file.

The input files look like this

{0,0,0,0,0,0,0,0,0} {1,1,1,1,1,1,1,} {3,3,3,3,3,3,3,3,3,3}

The number of digits vary from block to block and also the digits themselves are basically random. So I'd like to scan the input file for those blocks. This is what I got so far:

Pattern block = Pattern.compile("(\\{.*\\})");
    while(scanner.hasNext(block)){
        System.out.println(scanner.next(block));
    }

But so far, the program doesn't even enter the while statement. I don't know if my pattern is wrong or if I'm using the Scanner incorrectly.

And how do I take care of this whitespace between the blocks?

Thanks for your help!

2

There are 2 answers

0
Bohemian On

Define the delimiter - the pattern between tokens:

scanner.useDelimiter("(?<=\\{)\\s*(?=\\{)");

Then to loop simply:

while (scanner.hasNext()) {
    String term = scanner.next();
    // term will look like "{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }"
}
0
Francisco Romero On

Before initialize the Pattern if all the blocks have a space inside of them in the file, what I think that could be a possible solution its to read the file and replace all the spaces to a "" in the total String.

What I mean, for example, if you have stored your blocks in your file as a String like this (that it's only in one line):

{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 } {1 ,1 ,1 ,1 ,1 ,1 ,1 ,} {3 ,3 ,3 ,3 ,3 ,3 ,3 ,3 ,3 ,3 }

then you can read it with:

String test = scanner.nextLine();

and now that you have your String with all the blocks you can replace your " " to "". Something like this:

test = test.replaceAll(" ","");

Now you can print it in another file and read this second file to get all the blocks without the space.

I expect it will helps to you!