Removing spaces between single letters

后端 未结 8 2123
一向
一向 2021-01-07 06:01

I have a string that may contain an arbitrary number of single-letters separated by spaces. I am looking for a regex (in Perl) that will remove spaces between all (unknown n

8条回答
  •  天命终不由人
    2021-01-07 06:17

    It's not a regex but since I am lazy by nature I would it do this way.

    #!/usr/bin/env perl
    use warnings;
    use 5.012;
    
    my @strings = ('a b c', 'ab c d', 'a bcd e f gh', 'abc d');
    for my $string ( @strings ) {
        my @s; my $t = '';
        for my $el ( split /\s+/, $string ) {
            if ( length $el > 1 ) {
            push @s, $t if $t;
            $t = '';
            push @s, $el;
            } else { $t .= $el; }
        }
        push @s, $t if $t;
        say "@s";
    }
    

    OK, my way is the slowest:

    no_regex   130619/s         --       -60%       -61%       -63%
    Alan_Moore 323328/s       148%         --        -4%        -8%
    Eric_Storm 336748/s       158%         4%         --        -5%
    canavanin  352654/s       170%         9%         5%         --
    

    I didn't include Ether's code because ( as he has tested ) it returns different results.

提交回复
热议问题