user1883793 user1883793 - 1 year ago 128
Ruby Question

Ruby Regular expression to find the binary gap

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

enter image description here


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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download