• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

About regex

 
Ranch Hand
Posts: 2066
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could anyone please explains this code in detail.........


I couldn't catch up these behaviors..... Any suggestion regarding regex with related to SCJP 6 exam?

Thanks in Advanced~!
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your line 6 splits the input string into tokens based on a delimiter "any number of spaces (including 0), followed by fish, followed by any number of spaces".

This will split your string as follows: "1/ fish /2/ fish /red/ fish /blue/ fish", which gives you the tokens: "1", "2", "red", "blue".

The commented out line 7 is very similar, but because the delimiter doesn't include spaces, it splits the string as: "1 /fish/ 2 /fish/ red /fish/ blue /fish", which gives you the tokens: "1 ", " 2 ", " red ", " blue ". Note the spaces.

That would work. But then on line 9 you are trying to read the next token as an int. "1" converts to an int with no difficulties. But " 1 " doesn't, so it'll throw an exception using the second delimiter.

Does that explain what you wanted?
 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I haven't studies regex yet, but I modified the code as below:



I get the following output:


1
2
red
blue fish


Why does the last line output blue fish instead of just blue ?
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Sandra: Your delimiter is " fish ". Notice the space in the end. Now in the sample string the last fish doesn't have a space in the end.
So, this does not match the delimiter. Thats why it prints "blue fish".
Whereas, if the delimiter is "\\s*fish\\s*" then it will match zero or more space in the end.
 
reply
    Bookmark Topic Watch Topic
  • New Topic