Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regex in SCJP test

 
tural ferhadov
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,
I am trying to solve an scjp test about regex.

here is a code...

import java.util.regex.*;

public class TestRegex{
public static void main(String [] args){
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()){
System.out.print(m.start()+m.group());
}
}
}

and
java TestRegex "\d*" ab34ef
the answer is 01234456. I understood everything except the last output(6). Since the last index in "ab34ef" is 5, how is it possible to be printed 6 ?

Any help ....


 
Nancy Avent
Ranch Hand
Posts: 94
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
tural ferhadov wrote:hello,
I am trying to solve an scjp test about regex.

here is a code...

import java.util.regex.*;

public class TestRegex{
public static void main(String [] args){
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()){
System.out.print(m.start()+m.group());
}
}
}

and
java TestRegex "\d*" ab34ef
the answer is 01234456. I understood everything except the last output(6). Since the last index in "ab34ef" is 5, how is it possible to be printed 6 ?

Any help ....




Here is my try:
The expression "\d*" refers to any digit of length 0 or more; thus, it will match to all zero size matches too. The first match start before 'a' and end before 'a' (size zero match); this will print 0. What it means is the last match would be after 'f' (size zero match) and thus it will result in 6.
 
Adam Crawford
Greenhorn
Posts: 9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at this - I found this really useful when I was confused about the same thing.

Good luck!
 
tural ferhadov
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys, it really helped
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic