File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About regex Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About regex" Watch "About regex" New topic

About regex

Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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~!

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

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

Joined: Feb 18, 2010
Posts: 434
I haven't studies regex yet, but I modified the code as below:

I get the following output:

blue fish

Why does the last line output blue fish instead of just blue ?

Marriage Made in Heaven
Samrat Debroy

Joined: Oct 23, 2009
Posts: 13
@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.
I agree. Here's the link:
subject: About regex
It's not a secret anymore!