Removing spaces between single letters

后端 未结 8 2099
一向
一向 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:14

    This piece of code

    #!/usr/bin/perl
    
    use strict;
    
    my @strings = ('a b c', 'ab c d', 'a bcd e f gh', 'abc d');
    
    foreach my $string (@strings) {
       print "$string --> ";
       $string =~ s/\b(\w)\s+(?=\w\b)/$1/g; # the only line that actually matters
       print "$string\n";
    }
    

    prints this:

    a b c --> abc
    ab c d --> ab cd
    a bcd e f gh --> a bcd ef gh
    abc d --> abc d
    

    I think/hope this is what you're looking for.

提交回复
热议问题