• Post Reply Bookmark Topic Watch Topic
  • New Topic

scanner regex question  RSS feed

 
Tony Smith
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How is this producing "apples, oranges, pears" ?? I know it's suppose to be digit digit and space but I just can't figure out how is the program picking up the words. Can someone walk me step by step?

public class test {
public static void main(String[] args) {

String input = "10 apples 20 oranges 30 pears";
Scanner s = new Scanner(input).useDelimiter("\\d\\d\\s");
while (s.hasNext()){
System.out.print(s.next());

}
s.close();

}
[ September 01, 2007: Message edited by: Tony Smith ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this example, the regex is a delimiter, meaning it serves to "break up" the String. So given "10 apples 20 oranges 30 pears", it matches the delimiters "10 ", "20 ", and "30 ", which leaves the broken-out parts "apples", "oranges", and "pears".
 
Tony Smith
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright I figuered out, I originally thought //d would get a number no matter how long it is but rather it only pick up a single digit. So 10 is actually //d//d instead of one //d. That's what I was confused about.
[ September 01, 2007: Message edited by: Tony Smith ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!