Perl:将字符串分隔为具有公共字符的数组元素?

时间:2014-12-14 21:14:19

标签: arrays regex string perl expression

所以我想说我有一个字符串aaataagggggcccccccccccaa。如何将此字符串分解为只是一个普通字母的元素?

例如,我希望数组看起来像这样:

Element 1: 'aaa'
Element 2: 't'
Element 3: 'aa'
Element 4: 'ggggg'
Element 5: 'cccccccccc'
Element 6: 'aa'

1 个答案:

答案 0 :(得分:3)

使用Backreferences匹配重复的字符:

#!/usr/bin/env perl
use strict;
use warnings;

my $string = 'aaataagggggcccccccccccaa';
my @arry;

while ( $string =~ /((.)\2*)/g ) {
    push @arry, $1;
}

use Data::Dump;
dd @arry;

<强>输出:

("aaa", "t", "aa", "ggggg", "ccccccccccc", "aa")