|
-
Dec 2nd, 2004, 01:25 PM
#1
Thread Starter
Dazed Member
java.util.Scanner
I started taking a look at some of the new classes in Java5 but i am a bit confused on how a Scanner uses delimiters. For instance take the following block of code.
Code:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
What is the "\\s*" used for? If the delimiter was
specified as useDelimiter("fish"); wouldn't the output
still be the same?
Last edited by Dilenger4; Dec 6th, 2004 at 04:13 PM.
-
Dec 2nd, 2004, 05:19 PM
#2
The delimiter is any number of whitespace, then "fish", then again any number of whitespace.
With the current code, the output is
"1"
"2"
"red"
"blue"
(Lines intentionally wrapped in quotes for demonstration purposes.)
If you change the delimiter to "fish" the output will be
"1"
"2"
" red "
" blue "
Or perhaps it will even fail on nextInt.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Dec 3rd, 2004, 01:44 PM
#3
Thread Starter
Dazed Member
Re: java.util.Scanner
Ok according to the java.util.regex.Pattern documentation. "\\s*fish\\s*" contains what sun calls a greedy quantifier(X* X, zero or more times) and \s A whitespace character: [ \t\n\x0B\f\r]. I always thought parsing was done independent of the amount whitespace. Ive only ever tried to parse Strings using a StringTokenizer with single spaces between tokens.
-
Dec 3rd, 2004, 02:39 PM
#4
Re: java.util.Scanner
If you define that your parser should ignore whitespaces, then it will, but nothing in the definition of parser says so. A Scanner doesn't, by default, unless you tell it to by giving whitespace in the separator pattern.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Dec 4th, 2004, 01:00 PM
#5
Thread Starter
Dazed Member
Re: java.util.Scanner
Ok i see. You can use a Scanner to parse by white space independent of the amount of whitespace by using a greedy quantifer. Seems a lot more flexible then using a StringTokenizer where you can parse by space but not ignore the amount of space used.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|