Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding regex

 
B pandoo
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at the API for java.util.regex - the Pattern class and under Greedy Quantifiers.
 
Abdul Rehman
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic