user1883793 - 11 months ago 83

Ruby Question

I want to find the binary gap using Ruby regex

Say 1000001001010011100000000000, From left I want to use regex to match

A. 1000001 should return 00000

B. 1001 should return 0

C. 101 should return 0

D 1001 should return 00

My first attempt look like this but its missing the B and D

Update

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

Answer Source

I think what you are looking for is:

```
/1(0+)(?=1)/
```

The problem with your pattern is that you consume the "closing 1". Consequence, the next research starts after this "closing 1". But if you use a lookahead (that is a zero width assertion that doesn't consume characters and only tests what happens after), the "closing 1" isn't consumed and you get the desired result, because the next research starts after the last zero.

Note that if you don't need the zeros to be enclosed between ones, you can also simply use: `/0+/`

Other way: if you are sure that the string only contains 1 or 0, you can also use the (non-)word-boundary assertion `\B`

with this pattern: `\B0+\B`