• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

Regex

 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jelle Klap
 
This is awkward. I've grown a second evil head. I'm going to need a machete and a tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic