You get the same result because $
forces the end of the catching group to be at the end of the string. So, the fewest possible number of times will still necessarily go until the end of the string.
The ?
gets the *
or +
as few as possible, in contrast to the regex default that is to be "greedy", that is, to get as many matching characters as possible in the standard. Consider the following:
var string = 'Eu quero pegar uma palavra que comece com "q" seguida por um espaço.';
var re1 = /(q.*) /;
console.log(string.match(re1));
// "quero pegar uma palavra que comece com \"q\" seguida por um"
Notice that instead of picking up the "want", the capture group got the quero
, which starts with "q", and everything else until the last space found . That's why regex is greedy: it takes everything you can.
Now let's look at the same thing with ?
that takes greed out of regex:
var string = 'Eu quero pegar uma palavra que comece com "q" seguida por um espaço.';
var re2 = /(q.*?) /;
console.log(string.match(re2));
// "quero"
This is more in line with what we wanted. The regex got the capture group my word that starts with "q", and stopped in the first space ; that is, it gave match in the least number of possible characters that satisfies the regular expression.
In your original example, the smallest possible number of characters was still the complete string because with ^
and $
, you forced the regex to start at the first character of the string and end at the last one. So the smallest string that satisfies the complete expression is the whole string.