Split binary number into groups of zeros and ones

后端 未结 3 1619
离开以前
离开以前 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

    0 讨论(0)
  • 2021-01-19 14:04

    Just do matching instead of splitting.

    (\d)\1*
    

    Example:

    use strict;
    use warnings;
    use feature 'say';
    
    my $bin_string = '10000111000011';
    while($bin_string =~ m/((\d)\2*)/g) {
        print "$1\n";
    }
    

    IDEONE

    0 讨论(0)
  • 2021-01-19 14:06
    (?<=0)(?=1)|(?<=1)(?=0)
    

    Simply split by this.See demo.

    https://regex101.com/r/fM9lY3/3

    The lookarounds will find place where there is 0 behind and 1 ahead or 1 behind and 0 ahead.Thus resulting in correct split without consuming anything.

    0 讨论(0)
提交回复
热议问题