Forums Register Login

Obj 3.5:Regex,Searching using metacharacters

+Pie Number of slices to send: Send
Hi Folks,

With regards to the above, the following is the code:



The output when it is run with: "\d*"123a597b is:
Pattern is \d*
0 123
3
4 597
7
8

I don't understand the last digit 8. Even though there are 8 characters, I think the last number on the left should be 7 since the count starts from the value 0. Hope someone can advise. Thank you.
+Pie Number of slices to send: Send
 

John Paterson wrote:
I don't understand the last digit 8. Even though there are 8 characters, I think the last number on the left should be 7 since the count starts from the value 0. Hope someone can advise. Thank you.



The greedy quantifier * allows zero length matches also and that is why you see that 8.

You might want to refer to Oracle docs for how zero length matches work.

What it does is this.

Start at 0. Keep advancing greedily till you see zero or more digits. You get ..
0 123
Start at index 3 and keep advancing greedily till you see zero or more digits.
3 ---> zero length match.
.........
Start at index 7 and keep advancing greedily till you see zero or more digits.
7 ---> zero length match. ... Move further ( and this is by design ).
Next is index 8 - end of String. The zero length match applies here also and this is by design. So you get-
8 ---> zero length match.

You would get a similar behavior if you passed a zero length String argument to your program.
java Regex "\d*" ""
would, for example, print this.
0


+Pie Number of slices to send: Send
Hi Heena Agarwal,

Thanks for the explanation, appreciate it.

regards
John
A wop bop a lu bob a womp bam boom. Tutti frutti ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 530 times.
Similar Threads
SCJP 6 K&B book page no: 499
Regex problem
Locating Data via Pattern Matching
problems with regex
Illegal Escape Character
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 04:05:24.