-1

I can't figure out a way to get all possible matches. For the most basic example I have this:

"bbb".match(/bb/g);
//returns ["bb"] 

but I would like it to return ["bb","bb"] because bb matches with the first two b's and then again with the last 2 b's

In this example the possible matches are identical but they don't have to be for example :

"abab".match(/(.{1}).{1}\1/g);
//returns ["aba"]

Again here I was hoping for ["aba","bab"]

Is there a way to do that?

Philipp Werminghausen
  • 1,142
  • 11
  • 29
  • [How to get all possible overlapping matches for a string](http://stackoverflow.com/questions/18029487/how-to-get-all-possible-overlapping-matches-for-a-string) – Tushar Apr 07 '16 at 05:28
  • [Javascript Regex - Find all possible matches, even in already captured matches](http://stackoverflow.com/questions/14863026/javascript-regex-find-all-possible-matches-even-in-already-captured-matches) – Tushar Apr 07 '16 at 05:29
  • [Regex JavaScript overlapping matches](http://stackoverflow.com/questions/30942010/regex-javascript-overlapping-matches) – Tushar Apr 07 '16 at 05:29
  • [How to get possibly overlapping matches in a string](http://stackoverflow.com/questions/34964453/how-to-get-possibly-overlapping-matches-in-a-string) – Tushar Apr 07 '16 at 05:30

2 Answers2

1

Overlapping matches can be done by using positive lookahead like this.

Regex: (?=(bb))

Explanation:

  • It looks ahead for bb and captures it. Regex pointer is not at 2nd b which again looks ahead and captures bb, this time leaving the first one. It continues until end of string.

Regex101 Demo

  • 1
    It gives output `"bbb".match(/(?=(bb))/);` as `["", "bb"]` – gurvinder372 Apr 07 '16 at 05:24
  • @gurvinder372: Use back-referencing. Check **Match Information** section in regex demo. `.match()` returns all the matched subgroups. use `.exec()` –  Apr 07 '16 at 05:26
  • it looks good in the demo but if you actually try it in javascript with .match and .exec one of the resulting matches is an empty string – Philipp Werminghausen Apr 07 '16 at 05:39
  • All matches are empty strings in this case; you simulate the match with the first capture group. – Amadan Apr 07 '16 at 05:50
1

All matches found by match(/.../g) will be non-overlapping: once a match is found, regexp engine continues from the end of the match.

If you want to use this mechanism, you can't use the full match; but you can make use of lookahead and groups, as well as iteration. For example, this will work:

re = /bb/g;
var results = [];
while (matches = re.exec("bbb")) {
  results.push(matches);
  re.lastIndex -= matches[0].length - 1;
}
Amadan
  • 191,408
  • 23
  • 240
  • 301