It's not a secret anymore!
The moose likes Beginning Java and the fly likes Regarding Regular Expressions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding Regular Expressions" Watch "Regarding Regular Expressions" New topic
Author

Regarding Regular Expressions

Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 142
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

Joined: Oct 13, 2005
Posts: 44608
    
  34
Does this Java™ Tutorials link help?
Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 142
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
Sheriff

Joined: Sep 28, 2004
Posts: 20171
    
  47

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

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding Regular Expressions
 
jQuery in Action, 3rd edition