将二进制数拆分为一组 0 和 1 [英] Split binary number into groups of zeros and ones

查看:97
本文介绍了将二进制数拆分为一组 0 和 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制数,例如10000111000011,想把它分成连续的1和0组,1 0000 111 0000 11.

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 thought that's a great opportunity to use look-arounds: my regex uses a positive look-behind for a digit (which it captures for later backreferencing), then a negative look-ahead for that same digit (using a backreference), so I should get a split whenever a digit is followed by a digit that is not the same.

use strict;
use warnings;
use feature 'say';

my $bin_string = '10000111000011';
my @groups = split /(?<=(\d))(?!\g1)/, $bin_string;

say "@groups";

然而,这会导致

1 1 0000 0 111 1 0000 0 11 1

不知何故,捕获的数字会在每次拆分时插入.出了什么问题?

Somehow, the captured digit is inserted at every split. What did go wrong?

推荐答案

这是您代码的一个小修正:

Here is a small fix for your code:

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

您遇到的问题是,在使用 split 时,捕获的文本也会输出到结果数组中.所以,解决方案是去掉捕获组.

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.

由于您的输入中只有 01,因此通过交替和前瞻确保数字被更改非常容易.

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.

参见演示

这篇关于将二进制数拆分为一组 0 和 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆