Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Pattern & Matcher

Jennifer Moran
Ranch Hand
Posts: 60
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());
}
}

Can anyone explain THAT to me???

Thanks!!!

kshitij dogra
Ranch Hand
Posts: 39
Hi jennifer

In the code ,
Pattern p = Pattern.compile("\\d*");

you have asked the compiler to locate the data that contains either 0 or more digits.

So, I can split the answer for each data item as

LOC Data
0 -
1 -
2 34
4 -
5 -
6 - (no more)

Hope you get it

Jennifer Moran
Ranch Hand
Posts: 60
YES !!!

I get it.....it's the ZERO or more that confused me.

Thanks!!

Jennifer

Omar Al Kababji
Ranch Hand
Posts: 357
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)

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15568
46