regex - Splitting a string with multiple white spaces with perl?


Keywords:regex 


Question: 

I am trying to split a string with multiple white spaces. I only want to split where there are 2 or more white spaces. I have tried multiple things and I keep getting the same output which is that it splits after every letter. Here is the last thing I tried

@cellMessage = split(s/ {2,}//g, $message);
                foreach(@cellMessage){
                    print "$_ \n";
                }

5 Answers: 

@cellMessage = split(/ {2,}/, $message);
 

Keeping the syntax you used in your example I would recommend this:

@cellMessage = split(/\s{2,}/, $message);
                foreach(@cellMessage){
                    print "$_ \n";
                }

because you will match any whitespace character (tabs, spaces, etc...). The problem with your original code was that the split instruction is looking for a pattern and the regex you provided was resulting in the empty string //, which splits $message into individual characters.

 
use strict;
use warnings;
use Data::Dumper;

#                  1    22     333
my $message = 'this that  other   555';
my @cellMessage = split /\s{2,}/, $message;
print Dumper(\@cellMessage);

__END__

$VAR1 = [
          'this that',
          'other',
          '555'
        ];
 

You can actually do:

@cellMessage = split(/\s+/, $message);

It does the same thing as " @cellMessage = split(/ {2,}/, $message);" but looks a little cleaner to me imo.

 

Try this one: \b(\s{2,})\b

That should get you anything with multiple spaces between word boundries.