-1

I have a binary representation of a decimal:

1000010001

I want to match a sequence of consecutive zeros that is surrounded by ones at both ends, 10001.

So in my string there are two such occurrences:

100001
10001

But for some reason match with g returns only the first:

'1000010001'.match(/(?:10+1)+/ig)
> ["100001"]

Why not both? How to make it return all occurrences?

Green
  • 28,742
  • 61
  • 158
  • 247
  • The first match "consumes" the second `1` digit. You could back up the regex by 1 after each match if you did the matching in a loop. – Pointy Dec 09 '17 at 19:24
  • There is a dupe for this somewhere. I'm searching.... Bottom line is: when `100001` is matched, what left in the string is `0001` so applying the regex on the rest won't match. – ibrahim mahrir Dec 09 '17 at 19:28

1 Answers1

2

The matches consume characters, so after the first match, the string becomes 0001 and thus doesn't match the pattern anymore; You can turn the second 1 in the pattern into a look ahead assertion which doesn't consume characters, then add 1 to each match later:

var s = '1000010001';

console.log(
  s.match(/10+(?=1)/g).map(x => x + '1')
)
Psidom
  • 209,562
  • 33
  • 339
  • 356