How do I make a regex that would separate groups of the same digits from each other?

I am wondering whether I could write a regex that would help me, for instance, break up the String “122233444444666” into these Strings: “1”, “222”, “33”, “444444”, and “666”. In other words, I want to match not the groups themselves but the spaces between them. The regex is supposed to be used as a parameter for the split() method. The solution should be applicable to comma-separated digits too (e.g. “1,2,2,2,3,3,4,4,4,4,4,4,6,6,6”)


Is it possible to achieve with regex tools?

If you just need groups of equal digits, you could use the zero or more quantifier and the or operator after each digit: /(1*|2*|3*)?/g. For the array: join it and then apply the regex.

Wouldn’t it match the groups themselves, not the spaces between them?

Not sure which result you fancy exactly if your input string contains spaces. Why don’t you try the regex and see if it meets your expectations:

let regex = /(1*|2*|3*|4*|5*|6*|7*|8*|9*|0*)?/g;
let str = '12 2233444444666';
let result = str.match(regex);
console.log(result); // ["1", "2", "", "22", "33", "444444", "666", ""]

Easy filtering the empty strings:

console.log(result.filter(el => el)); // ["1", "2", "22", "33", "444444", "666"]

The thing is I wanted that regex to be used as a parameter for the split() method. It should take, for example, "12233666" and return an array of Strings: ["1", "22", "33", "666"]. That’s why I provided that pseudo-regex


Notice how it makes use of a lookbehind and a lookahead. The digit groups themselves are not supposed to be captured