This week's book giveaway is in the Design forum. We're giving away four copies of Building Microservices and have Sam Newman on-line! See this thread for details.

Whoa !!! I am sooo confused regarding this subject.

Question is:

public static void main(String[] a) {
Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher("ab34ef");
boolean b = false;
while (b = m.find()) {
System.out.println(m.start() + m.group());
}
}

Hi, i will be your nice compiler here is what you get for each iteration

first this pattern will search for zero or more digits since you are using the * your string is "ab34ef"

1. first match is "a" and it can be applied to "zero or more digits" so you get
m.find() = 0
m.group() = empty string
output on the console = 0

2. second match is "b" and it can be applied to "zero or more digits" so you get
m.find() = 1
m.group() = empty string
output on the console = 01

3. third match is "34" and it can be applied to "zero or more digits" so you get
m.find() = 2
m.group() = 34
output on the console = 01234

*note that for the (3) mathch it didn't toke only the "3" but it took the "34" match since the wildcards are "greedy" they will try to mach as much as possible of the string.

4. forth match is "e" and it can be applied to "zero or more digits" so you get
m.find() = 4
m.group() = empty string
output on the console = 012344

5. fith match is "f" and it can be applied to "zero or more digits" so you get
m.find() = 5
m.group() = empty string
output on the console = 0123445

6. finally nothing remains in the string which maches "zero or more digits" so you get
m.find() = 6
m.group() = empty string
output on the console = 01234456

done.

;) hope you got it, its a bit tricky

(peace)

Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog