Can any one help me to understand the difference between two approaches to regular expressions, with some suitable examples?
Thanks
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With