首页 > 解决方案 > 如何使用正则表达式对不同的字母(不一定是连续的)进行分组

问题描述

下面的示例按预期结果:

const str = "abbcccddddeeeeeffffff";

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

console.log(res);

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

const str = "abxbcxccdxdddexeeeefxfffffxx";

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

console.log(res);

我想得到这样的东西:

[ 'a', 'bb', 'xxxxxxx', 'ccc', 'dddd', 'eeeee', 'ffffff']

标签: javascriptregex

解决方案


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

const str = "abxbcxccdxdddexeeeefxfffffxx";

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

console.log(res);

如果您绝对希望它们按该顺序排列,则可以对字符串进行去重并单独匹配字母

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


推荐阅读