JohanP
JohanP

Reputation: 5472

Capturing repeated groups

I have this string 1xxx5xx1x7xxx8. I want to get matches so that I have the following results:

match[0] = '1xxx5'
match[1] = '5xx1'
match[2] = '1x7'
match[3] =  '7xxx8'

So the basic pattern is get groups that have 1 or more x between digits. I have this basic regex so far but it doesn't work:

/\dx{1,}\d/

The string that I have used is just an example, the patterns could continue on for as long as what the string is.

Upvotes: 1

Views: 58

Answers (2)

pushkin
pushkin

Reputation: 10199

Regex engines don't support overlapping matches, but you can use the trick in Paulpro's answer. Or you can write your own algorithm for this:

var myString = "1xxx5xx1x7xxx8";
var matches = [];
var curMatch = "";
for (var i = 0; i < myString.length; ++i) {
  var char = myString[i];
  if (char === "x") { // assumes you only have numbers or x's
    curMatch += char;
    continue;
  }

  if (curMatch) {
      matches.push(curMatch + char);
  }

  curMatch = char;
}

console.log(matches)

Upvotes: 1

Paul
Paul

Reputation: 141829

You can use RegExp.prototype.exec to find matches one at a time and decrement lastIndex in between to start searching for next match with one character of overlap:

var str = '1xxx5xx1x7xxx8';
var regex = /\dx+\d/g;

var matches = [], match;
while ( match = regex.exec( str ) ) {
  matches.push( match[ 0 ] );
  regex.lastIndex--; // Start next search one char back (overlap matches)
}

console.log( matches );

Upvotes: 2

Related Questions