Split binary number into groups of zeros and ones

后端 未结 3 1618
离开以前
离开以前 2021-01-19 13:29

I have a binary number, for example 10000111000011, and want to split it into groups of consecutive 1s and 0s, 1 0000 111 0000 11.

I though

3条回答
  •  爱一瞬间的悲伤
    2021-01-19 13:55

    Here is a small fix for your code:

    my @groups = split /(?<=0(?!0)|1(?!1))/, $bin_string;
    

    The problem you experience is that when using split captured texts are also output in the resulting array. So, the solution is to get rid of the capturing group.

    Since you only have 0 or 1 in your input, it is pretty easy with an alternation and a lookahead making sure the digits get changed.

    See demo

提交回复
热议问题