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

Obj 3.5:Regex,Searching using metacharacters

 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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


 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Heena Agarwal,

Thanks for the explanation, appreciate it.

regards
John
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic