Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.util.Scanner

 
Lorenz Baylon
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

lhorenz
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Lorenz Baylon
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
lineScanner.useDelimiter("^.*Name:\\s*");

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

lhorenz
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>


O/P:
 
Lorenz Baylon
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cool! really! thanks a lot folks! It really helps me a lot!

Best regards,
lhorenz
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scanner class is a cool addition to JDK 1.5
 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OMG! OMG! It's Lhorenz!

Java sure have made a lot of things available these days...
 
Lorenz Baylon
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hehe hi Tim!
Follow question.. how do I use Scanner with binary files?

Thanks thanks thanks!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic