下面的示例按预期结果进行:
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)
在应用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)
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |