This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding regex 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 "Regarding regex" Watch "Regarding regex" New topic
Author

Regarding regex

B pandoo
Ranch Hand

Joined: Nov 14, 2006
Posts: 37
public class Sting
{
public static void main(String[] args){
String str = "aaaaaaaaabb";
String[] s = str.split("a{3}");
System.out.println(s.length);
}
}

Answer is 4.
pleas explain the output..
what does a{3} represents?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Look at the API for java.util.regex - the Pattern class and under Greedy Quantifiers.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Abdul Rehman
Ranch Hand

Joined: Nov 07, 2006
Posts: 65
The regex "a{3}" means the character 'a' exactly 3 times.
To understand the output, you should know how the split() method works. See the API for this method in the java.util.regex.Pattern class.
After that, try playing with the code. Here is a modified version of the code alongwith the output.

This gives the output:

4
x
x
x
bb


Think out why we get such an output? Once done, look at your own code. The only change is that the 'x' characters have been omitted in your version. So, think out why the output is 4?

Regards,
Abdul Rehman.


SCJP 5.0 (100%)
 
GeeCON Prague 2014
 
subject: Regarding regex