In some Rails code (cucumber features’ steps definitions, javascripts, rails_admin gem) I found this regular expression parts:
string =~ /some regexp.+rules should match "(.*?)"/i
I do have some knowledge at regular expressions and i know that * and ? symbols are similar but whilst asterisk means zero and more, the question mark means could be present or could be not.
So, using the question mark near the group of symbols makes its presence non-required within the phrase being tested. What’s the… well… the trick of using it near the non-required already group (skipping requirement is made using the asterisk afaik)?
Right after a quantifier (like
*), the?has a different meaning and makes it “ungreedy”. So while the default is that*consumes as much as possible,*?matches as little as possible.In your specific case, this is relevant for strings like this:
Without the question mark the regex matches the full string (because
.*can consume"just like anything else) andsome string" or "anotheris captured. With the use of the question mark, the match will stop as soon as possible, (so after...some string") and will capture onlysome string.Further reading.