File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes SCJP6 study - regex string.split - strange results, can anyone explain please? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "SCJP6 study - regex string.split - strange results, can anyone explain please?" Watch "SCJP6 study - regex string.split - strange results, can anyone explain please?" New topic
Author

SCJP6 study - regex string.split - strange results, can anyone explain please?

Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
eg based on a whizlabs q:



The length of s is: 5

0
1 12
2
3
4 2

I was expecting even numbers of 1's ie 11 to disappear, so I would have 122 remaining.
It has removed 6 pairs of 11. How do you account for the way it is storing nulls?
>


Nigel
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40


Start with the original string...

"111211111121111"


Do a regex find to get the delimiters...

"11 12 11 11 11 2 11 11"


Add "X" to show the blank tokens...

"X 11 12 11 X 11 X 11 2 11 X 11 X "


Remove the trailing blanks, because you used the version of split() that removes them...

"X 11 12 11 X 11 X 11 2"


So, you get a final result of 5 tokens, which are blank, 12, blank, blank, and 2.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 791

@Henry
Great explaination.


SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140

Hi Henry, I really appreciate the reply, the penny has dropped!

I've created a more complex example and managed to predict the result.

Cheers!
 
GeeCON Prague 2014
 
subject: SCJP6 study - regex string.split - strange results, can anyone explain please?