Vladdy
Vladdy

Reputation: 31

file parsing using tokens

I have a text file that reads as follows:

item1, description # brand1, brand2

item2, description # brand3

I have an array list of brands and another array lists of items.

My code reads and assigns everything until it gets to the "#" after the item description...

    while(input.hasNextLine())
        {
            String line = input.nextLine();
            String[] token = line.split("[,#]+");

            item = token[0];
            description = token[1];

            brand = token[2];

        }  

How can I get it to properly read what's after the "#" ?? I should mention that an item can belong to 2 or more brands

Upvotes: 0

Views: 54

Answers (2)

Scherling
Scherling

Reputation: 1390

I believe what you're looking for is regular expressions (regex)

It allows you set up a pattern that defines how the data is structured like this:

"(?<item>.+),\s(?<description>.+)\s\#\s(?<brands>.+)"

(disclaimer: just a quick example written by hand, might not work correctly) And then apply the pattern to a string using a matcher.

I'd strongly suggest you read up on regex, or take a tutorial on it. It's super useful. check out: http://docs.oracle.com/javase/tutorial/essential/regex/intro.html

Upvotes: 0

Sezin Karli
Sezin Karli

Reputation: 2525

First split by "#" process the result and then by ",".

Upvotes: 1

Related Questions