-2

I'm trying to solve a binary gap problem using regex and I'm having some problems getting it to work.

If I try something like this:

Number(101001000).toString().match(/(1[0]+1)/g)

It returns only ["101"], when I'm expecting ["101", "1001"].

Am I doing something wrong or it's not possible to achieve this result with regex only?

  • 2
    Your matches are overlapping. See also: https://stackoverflow.com/questions/20833295/how-can-i-match-overlapping-strings-with-regex – Mark Sep 13 '20 at 04:09

2 Answers2

-1

function binaryGap(binStr) {
  return (
    binStr
    .split("1")
    .reduce((acc,cv,idx,arr)=>{
      if(idx&&idx<arr.length-1)
        acc.push(1+cv+1);
      return acc;
    },[])
  );
}

console.log(binaryGap(Number(101001000).toString()));
console.log(binaryGap("00101001000"));
console.log(binaryGap("001010011000"));
iAmOren
  • 2,760
  • 2
  • 11
  • 23
-1

It is possible to do this with regex only, but don't match the terminating 1, as it may need to be part of a next match.

Instead, just require that there is a 1 just after your match without actually grabbing it.

If in the output you still want to include that terminating 1, then just map the match result accordingly:

console.log(
   (101001000).toString().match(/10+(?=1)/g).map(m => m + "1")
)

Some other remarks:

  • you don't really need to call Number, as 101001000 is already a number. The only reason you need to do something extra, is resolving the ambiguity of the dot in .toString. But parentheses are enough to do just that. You could even just add an extra dot: 101001000..toString() will also work.

  • There is no need in your regex to wrap 0 in square brackets, nor to wrap the whole expression in parentheses.

trincot
  • 317,000
  • 35
  • 244
  • 286