1

If I clearly understand then in this example match finds all strings with length 0. And empty strings are in the beginning, ending and between all symbols in string so there are 11 empty string

const str = '0123456789';
const regexp = /|/g;
const matches = str.match(regexp);

console.log('Length = ' + matches.length);
console.log(matches);

In this example everything is clear. I just search digits so there are 10 digits:

const str = '0123456789';
const regexp = /\d/g;
const matches = str.match(regexp);

console.log('Length = ' + matches.length);
console.log(matches);

But I don't understand why I cann't get 21 matches when trying to combine 2 regexp:

const str = '0123456789';

const regexp1 = /|\d/g;
const matches1 = str.match(regexp1);
console.log('Length = ' + matches1.length);
console.log(matches1);

const regexp2 = /\d|/g;
const matches2 = str.match(regexp2);
console.log('Length = ' + matches2.length);
console.log(matches2);
EzioMercer
  • 1,502
  • 2
  • 7
  • 23
  • `|` is actually treated as a kind of "ordered choice": First try the left exp, then try the right one. – Luatic Jun 26 '22 at 15:56
  • 3
    It gives at most one match per startIndex. Kind of similar to [Get overlapping matches from regex javascript (ALLOW SAME INDEX) - Stack Overflow](https://stackoverflow.com/questions/67237505/get-overlapping-matches-from-regex-javascript-allow-same-index) I guess, although answers there are not generalizable. – user202729 Jun 26 '22 at 16:10
  • @LMD I understand how does it work. And I expected that this regexp will give me `['','0','','1','','2','','3','','4','','5','','6','','7','','8','','9','']` because I have 11 empty string and 10 digits – EzioMercer Jun 26 '22 at 16:26
  • 2
    That is because of how empty matches are handled. You won't get this even with overlapping matches, because when there is an empty match, the index is forced to the positon before the next char. – Wiktor Stribiżew Jun 26 '22 at 21:18
  • Thank you all guys for your explanation! – EzioMercer Jun 26 '22 at 21:38

1 Answers1

3

Why can't I get 21 matches when trying to combine the 2 regexp?

Because .match() returns non-overlapping matches. It will not cover the same character (in each position) with multiple matches, and for empty matches it will not return multiple matches starting at the same index.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375