字符串等长划分

正则表达式、字符编码、字符处理

字符串等长划分

帖子523066680 » 2015-12-26 11:19

链接:
Using split() to divide a string by length

Re: Using split() to divide a string by length
by Zaxo on Apr 13, 2006 at 19:39 UTC

Another trick that works is to capture the split characters, which places them also in @fields and makes pos advance beyond them. Since all but probably the last group match, the normal split results mostly don't contain anything, so we need to filter out false elements with grep:

代码: 全选
    my $string = join '', a..z;

    my @fields = grep {$_} split /(.{3})/, $string;

    print "@fields\n";

    __END__
    abc def ghi jkl mno pqr stu vwx yz

After Compline,
Zaxo


Re: Using split() to divide a string by length
by BrowserUk on Apr 13, 2006 at 20:08 UTC

I find unpack more suitable for this task.

代码: 全选
    print for unpack '(A3)*', "abcdefghi";;
    abc
    def
    ghi

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.


扩展后是这样的:
代码: 全选
for (unpack '(A3)*', "abcdefghi")
{
    print $_, "\n";
}


Re: Using split() to divide a string by length
by chibiryuu on Apr 13, 2006 at 20:10 UTC

This doesn't use split, but is the first thing I think of:

代码: 全选
    my $string = join '', 'a'..'z';
    my @fields = $string =~ /.{1,3}/g;
    my @fields2 = grep {$a=!$a} @fields;

Hmm, $string =~ /.{1,3}/g should even be faster than split /(?(?{pos() % 3})(?!))/, $string. I guess not as fast as unpack, though.
论坛已转移 Code-By.Org 群号 322023604
头像
523066680
版主
 
帖子: 1680
注册: 2012-03-06 15:08

回到 文本处理

在线用户

正在浏览此版面的用户:没有注册用户 和 1 位游客

cron
Not able to open ./cache/data_global.php