Mihai
Mihai

Reputation: 26784

Find adjacent groups in a string

I need to find how many large groups are in a string s. A small group is simply a contiguous segment(same character repeats). A large group is a contiguous segment formed from 2 or more small groups.

It`s clearer with code,below I get all the small groups

var s = "ccccoodeffffiiighhhhhhhhhhttttttts";

sgroups= s.match(/(.)\1+/g);
console.log(sgroups)

How do I find the large groups?

"ccccoo",
 "ffffiii",
 "hhhhhhhhhhttttttt"

In another example

var s = "soooooldieeeeeer";
var sgroups= s.match(/(.)\1+/g);
console.log(sgroups)

In the code above,since the 2 small groups are not contiguous in the original string,there are no large groups.

Upvotes: 1

Views: 306

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627190

You may use:

var rx = /(?:(.)\1+(?!\1)){2,}/g;
console.log("soooooldieeeeeer".match(rx));
console.log("soooooldieeeeeerrr".match(rx));

Details:

  • (?: - start of a non-capturing group (does not create a numbered capture for us to be able to still use \1 backreference later and keep the match "clean")
    • (.) - capturing group 1 matching any char (but a line break char)
    • \1+ - one or more occurrences of the same char as stored in Group 1 (where \1 is the backreference to the value kept in Group 1 and + is a one or more occurrences quantifier)
    • (?!\1) - makes sure the chunk of identical characters is not followed with the same char, so as not to allow backtracking match strings where 4 or more consecutive identical characters appear.
  • ){2,} - two or more occurrences of the non-capturing group pattern.

Upvotes: 4

Related Questions