Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding matches using regular expression

How to find the length of consecutive zeros that is surrounded by ones at both ends of a binary?

For example, in 10010001 the 2 matches are 1001 and 10001

  • 1001 the length of zeroes is 2
  • 10001 the length of zeroes is 3

I used match which returned only the last one i.e. 10001.

'1010001'.match(/1(0+)1$/g)
like image 819
Kapil gopinath Avatar asked Feb 27 '26 14:02

Kapil gopinath


1 Answers

You need lookahead assertions here:

console.log('1010001'.match(/10+(?=1)/g).map(function(x) {
   return x.length - 1;
}));
like image 141
revo Avatar answered Mar 02 '26 05:03

revo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!