• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regex  RSS feed

 
Varnam Aayiram
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

I have a regex related question:

Following is the code:



following is the invocation:

% java Regex "a?" "aba"




and the following is the output:

Pattern is a?
0 a
1
2 a
3


How is 3 even possible? I thought the index should read as ("0,1,2"). Hope someone can advise. Thanks.
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at this SCJP FAQ entry, which explains this quite nicely.
The cliff notes version: the ? in the regex pattern is a greedy quantifier, which matches zero-length occurances of the preceeding pattern segment - in this case a zero-length occurance of "a" at index 3.
The fact that the index returned is beyond what you'd expect possible give the length of te String adds to the confusion a bit, but that's related to how the Matcher processes the input.
More info on zero-length matches here.
 
Varnam Aayiram
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jelle Klap
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!