From: "RadosÅ‚aw BuÅ‚at" Date: 2008-01-17T20:17:59+09:00 Subject: Re: Greedy and non greedy quantifiers There are 4 (I hope that didn't miss anything) operators to specify repetitions. *, +, ? and {m, n} * - matches 0 or more + - matches 1 or more ? - matches 0 or 1 (same as {0,1} ) {m,n} matches m..n All these operators all greedy (I'll show you examples). To make non-greedy operator you must add '?' after operator. So non-greedy operators are: *?, +?, ??, {m,n}? *? - matches 0 or more +? - matches 1 or more ?? - matches 0 or 1 (same as {0,1}?) {m,n} matches m..n Maybe '??' looks strange, but all of these are absolutely correct. So far no differences. Why we have greedy and non-greedy operators? Because they works in different way. Greedy operators tries to match as many character (precisely: left expression) as can and if during matching it must move back it tries to match fewer characters. For example: puts "aaaa".match(/a*/) # matches whole string puts "aaaa" =~ /a*?/ # matches no characters (but it success) Another example: puts "aaaabaaaab".match(/.*b/) # matches whole string puts "aaaabaaaab".match(/.*?b/) # matches "aaab" I always recommend Jeffrey Friedl's book "Mastering Regular Expressions" (http://regex.info/). After reading this book you will be master of regexp ;-). -- Rados³aw Bu³at http://radarek.jogger.pl - mój blog