Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group different letters (not necessarily consecutive) using a regex

The example below results as expected:

const str = "abbcccddddeeeeeffffff";

const res = str.match(/(.)\1*/g);

console.log(res);

But if I try to group non consecutive letters:

const str = "abxbcxccdxdddexeeeefxfffffxx";

const res = str.match(/(.)\1*/g);

console.log(res);

I would like to get somethig like this:

[ 'a', 'bb', 'xxxxxxx', 'ccc', 'dddd', 'eeeee', 'ffffff']
like image 985
Emeeus Avatar asked Mar 03 '23 08:03

Emeeus


1 Answers

Sort the string before applying the Regex :

const str = "abxbcxccdxdddexeeeefxfffffxx";

const res = [...str].sort().join('').match(/(.)\1*/g);

console.log(res);

If you absoloutely want them in that order, you can dedup the string and match the letters individually

const str = "abzzzbcxccdxdddexeeeefxfffffxx";

const res = [];

[...new Set(str)].forEach(letter => {
  const reg = new RegExp(`${letter}`, "g");
  res.push(str.match(reg).join(""));
});

console.log(res);
like image 169
Taki Avatar answered May 11 '23 23:05

Taki