Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between greedy and non-greedy approach to Regular expression in Ruby?

Tags:

regex

ruby

Can any one help me to understand the difference between two approaches to regular expressions, with some suitable examples?

  • greedy
  • non-greedy

Thanks

like image 288
DoLoveSky Avatar asked Dec 08 '22 18:12

DoLoveSky


1 Answers

In greedy approach regex pattern tend to consume maximum characters in a source string.For example

textstr = "bcabdcab"
textstr.gsub!(/(.*)ab/, "xxx")  
# this will match whole `bcabdcab` and return `xxx`

Here * is a greedy quantifier.In non greedy approach regex engine returns when it satisfies the matching criteria.To make a quantifier non-greedy append ?

textstr = "bcabdcab"
textstr.gsub!(/(.*?)ab/, "xxx")  
# this will match only `bcab` part and return `xxxdcab`

gsub returns a copy of str(first argument) with the all occurrences of pattern substituted for the second argument

like image 174
Varinder Singh Avatar answered Dec 11 '22 09:12

Varinder Singh