Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About regex

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • 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~!
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • 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?
 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • 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 ?
 
Samrat Debroy
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic