regex - Split binary number into groups of zeros and ones -
i have binary number, example 10000111000011
, , want split groups of consecutive 1s , 0s, 1 0000 111 0000 11
.
i thought that's great opportunity use look-arounds: regex uses positive look-behind digit (which captures later backreferencing), negative look-ahead same digit (using backreference), should split whenever digit followed digit not same.
use strict; use warnings; use feature 'say'; $bin_string = '10000111000011'; @groups = split /(?<=(\d))(?!\g1)/, $bin_string; "@groups";
however, results in
1 1 0000 0 111 1 0000 0 11 1
somehow, captured digit inserted @ every split. did go wrong?
here small fix code:
my @groups = split /(?<=0(?!0)|1(?!1))/, $bin_string;
the problem experience when using split
captured texts output in resulting array. so, solution rid of capturing group.
since have 0
or 1
in input, pretty easy alternation , lookahead making sure digits changed.
see demo
Comments
Post a Comment