如何使用正则表达式将不同的字母(不一定是连续的)分组

Eme*_*eus 4 javascript regex

下面的示例按预期结果进行:

const str = "abbcccddddeeeeeffffff";

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

console.log(res);
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试对非连续字母进行分组:

const str = "abxbcxccdxdddexeeeefxfffffxx";

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

console.log(res);
Run Code Online (Sandbox Code Playgroud)

我想得到这样的东西:

[ 'a', 'bb', 'xxxxxxx', 'ccc', 'dddd', 'eeeee', 'ffffff']
Run Code Online (Sandbox Code Playgroud)

Tak*_*aki 7

在应用Regex之前对字符串进行排序:

const str = "abxbcxccdxdddexeeeefxfffffxx";

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

console.log(res);
Run Code Online (Sandbox Code Playgroud)

如果您绝对要按顺序排列它们,则可以将字符串分离并分别匹配字母

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);
Run Code Online (Sandbox Code Playgroud)