Home > Mobile >  Cann't combine two regexp in str.match() to get combined results
Cann't combine two regexp in str.match() to get combined results

Time:06-27

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);

CodePudding user response:

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.

  • Related