user2426260
user2426260

Reputation: 1

Using multiple delimiters with scanner - Java

I'm trying to use both tabs and newlines as delimiters to read from a .txt file. What I have at the moment is:

Scanner fileScanner = new Scanner(new FileReader("propertys.txt"));

fileScanner.useDelimiter("[\\t\\n]");

I've tried:

fileScanner.useDelimiter("\\t|\\n");

and

fileScanner.useDelimiter("[\\t|\\n]");

I've got no idea what's going wrong, I've searched around a lot and it looks like one of those should be working. Clearly I'm doing something wrong.

Upvotes: 0

Views: 6385

Answers (2)

Dakota Chambers
Dakota Chambers

Reputation: 11

fileScanner.useDelimiter("\t|\n"); should work.

If you have two slashes "\n" the first acts as an escape and it won't work right.

Upvotes: 1

Lucia Pasarin
Lucia Pasarin

Reputation: 2308

For the regular expression used as a parameter in useDelimiter method, you should use newline as \n instead of \\n and tab as \t instead of \\t. From Java Pattern class: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html.

A part from that, I think you should define you regular expression like, for example, this:

fileScanner.useDelimiter("\\s*[\t\n]\\s*");

to limit strings (\\s) between newline or tab characters.

Upvotes: 0

Related Questions