Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Regular Expressions

 
Raj chiru
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

can you please explain What is differences among Greedy,Reluctant, and Possesive Quantifiers with example?
Actually I'm confusing with these Quantifiers.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does this Java™ Tutorials link help?
 
Raj chiru
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi campbell,
Thanks For Your Reply,


Enter your regex: .*+foo // possessive quantifier
Enter input string to search: xfooxxxxxxfoo
No match found.


why we got No match found here?
 
Henry Wong
author
Marshal
Pie
Posts: 21385
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
raj chiru wrote:
Enter your regex: .*+foo // possessive quantifier
Enter input string to search: xfooxxxxxxfoo
No match found.


why we got No match found here?


Because of the way the possessive modifier works. The possessive modifier acts like the greedy modifier, except that it doesn't back off. So...

The ".*+" portion will match everything, just like a greedy modifier. However, if it does that, while the ".*+" portion will match, the overall match will fail since there isn't anything left for the "foo" portion of the regex to match. In the case of the greedy modifier, it will backtrack, and match less, in order to allow the overall match to work.

Unfortunately, in the case of the possessive modifier, there isn't a backtrack, and hence, the overall match will fail. This is why you have to be really careful with the posessive modifier -- only use it for cases where you can perform the match correctly without a backtrack, because it won't.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic