Niklas
Niklas

Reputation: 131

Java: Parse lines from files

I am in need of some ideas. I have a file with some information like this:

AAA222BBB% CC333DDDD% EEEE444FF%

The '%' sign is like an indicator of "end of line"

I would like to read every line, and then parse it to fit a certain format (4 letters, 3 digits and 4 letters again) - So if it looks like the above, it should insert a special sign or whitespace to fill, like this:

AAA-222BBB-% CC--333DDDD% EEEE444FF--%

My first and immediate idea was to read every line as a string. And then some huge if-statement saying something like

For each line:
{
    if (first symbol !abc...xyz) {
        insert -
    }

    if (second symbol !abc...xyz) {
        insert -
    }
}

However, I am sure there must be a more elegant and effective way, do to a real parsing of the text, but I'm not sure how. So if anyone has a good idea please enlighten me :-)

Best

Upvotes: 0

Views: 755

Answers (1)

Sergio F
Sergio F

Reputation: 26

My first advice is to read this other post (nice explanation of scanner and regex): How do I use a delimiter in Java Scanner?

Then my solution (sure it is the the cleverest, but it should work)

For each line:
{
    Scanner scan = new Scanner(line);
    scan.useDelimiter(Pattern.compile("[0-9]"));
    String first = scan.next();

    scan.useDelimiter(Pattern.compile("[A-Z]"));
    String second = scan.next();

    scan.useDelimiter(Pattern.compile("[0-9]"));
    String third = scan.next();

    scan.close();

    System.out.println(addMissingNumber(first, 4) + addMissingNumber(second, 3) + addMissingNumber(third, 4));
}

 //For each missing char add "-"
 private static String addMissingNumber(String word, int size) {
    while (word.length() < size) {
        word = word.concat("-");
    }
    return word;
 }

The output: "AAA-222BBB-"

Upvotes: 1

Related Questions