Regex / A? / G does not match multiple A characters

Why /A?/gdoes a regex match only the first capital A in a string? From what I understand, if I executed the following code

reg = /A?/g;
match1 = reg.exec('AaAa');
match2 = reg.exec('AaAa');
match3 = reg.exec('AaAa');
console.log(match1, match2, match3); //["A"], [""],[""]

I can’t fix the second appearance of “A”. What for? It seems to me that though? makes A optional, since its greedy, shouldn't it include the second “A” in the 2nd match?

+4
source share
1 answer

When you use exec, the regex object "remembers" the index of the last match.

Allows you to record the value lastIndex:

reg = /A?/g;
reg.exec('AaAa');
console.log(reg.lastIndex); // 1
reg.exec('AaAa');
console.log(reg.lastIndex); // 1
reg.exec('AaAa');
console.log(reg.lastIndex); // 1

As you can see, the index of the last match does not change! But why?

, (?).

exec , 1, "a", A?. , A? , .. "a". , , , , . .

-:

AaAa // does index 0 match "A?" ? Yes, consume "A" and increase index to 1
^
AaAa // does index 1 match "A?" ? Yes, but do not consume "a"
 ^
AaAa // does index 1 match "A?" ? Yes, but do not consume "a"
 ^
...

exec "a".

exec MDN.


, , .

+4

Source: https://habr.com/ru/post/1615503/


All Articles