Takkun
Takkun

Reputation: 6361

Get words that are separated by various number of spaces with regex?

I'm trying to grab each word in the string that can be separated by various number of whitespaces.

my $ff = "Disk  DSM     Policy  Paths   Serials";

if($ff =~ m/(\w+)/) {
    print $1;
    print $2;
    print $3;
}

I thought it would be as simple as \w but it only gets the first word? Am I doing something wrong?

Upvotes: 0

Views: 905

Answers (1)

daxim
daxim

Reputation: 39158

You need to match globally.

my $ff = "Disk  DSM     Policy  Paths   Serials";

my (@words_match) = $ff =~ /(\w+)/g;
# (
#     'Disk',
#     'DSM',
#     'Policy',
#     'Paths',
#     'Serials'
# )

A better solution is to split.

my @words_split = split ' ', $ff;
# (
#     'Disk',
#     'DSM',
#     'Policy',
#     'Paths',
#     'Serials'
# )

Upvotes: 5

Related Questions