Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes java.util.Scanner Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java.util.Scanner" Watch "java.util.Scanner" New topic


Lorenz Baylon
Ranch Hand

Joined: Jan 04, 2006
Posts: 99
Hi, im trying to parse a text file using the java.util.Scanner.
my trouble is that by default, the Scanner parses the line like this:

(example line) Joe: 38

when i parse this line using the pattern ':' , what i get is 'Joe'.
what i want to achieve is to parse the line so that i will be able to get '38' instead.

Thanks a lot in advance.


I just cant look, its killing me.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
I'd try something like

If that doesn't work for you, please provide some more sample lines of the file to see what sort of variety you have there.

"I'm not back." - Bill Harding, Twister
Lorenz Baylon
Ranch Hand

Joined: Jan 04, 2006
Posts: 99
Thank you, it works!

Can we try it for a line in my real world?
the line goes like this:

String theLine = "Name: lhorenz AreaCode: 054 Book: 0012C Page: 00260";

I've tried using:
Scanner lineScanner = new Scanner(theLine);

the result is " lhorenz AreaCode: 054 Book: 0012C Page: 00260"

maybe you could give me a hint so i could just get "lhorenz" for the value of "Name:", "054" for AreaCode and so on.

I really appreciate the help, I really dont want to resort to using substring method and other String methods as much as possible.

Again, many thanks and regards

Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
You can do it using the java.util.regex.Pattern and java.util.regex.Matcher classes. There's a little bit of a learning curve involved though.

O/P =

Alternatively you can capture the attrribute type, and name and add them to a Map<String, String>


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Lorenz Baylon
Ranch Hand

Joined: Jan 04, 2006
Posts: 99
Cool! really! thanks a lot folks! It really helps me a lot!

Best regards,
ak pillai
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
Scanner class is a cool addition to JDK 1.5

java j2ee job interview questions with answers | Learn the core concepts and the key areas
Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 751
OMG! OMG! It's Lhorenz!

Java sure have made a lot of things available these days...

SCJP 1.5
Lorenz Baylon
Ranch Hand

Joined: Jan 04, 2006
Posts: 99
hehe hi Tim!
Follow question.. how do I use Scanner with binary files?

Thanks thanks thanks!
I agree. Here's the link:
subject: java.util.Scanner
jQuery in Action, 3rd edition