0

I want to split a string by everything but whitespaces.

Example:

Assume that I have a string:

"The    quick  brown fox    jumps over   the lazy dog"

I want to split it and get the following list of space-strings:

["    ", "  ", " ", "    ", " ", "   ", " ", " "]

Can you please show me how to do it?

Thanks!

SomethingSomething
  • 11,491
  • 17
  • 68
  • 126

3 Answers3

2

You can use \S to split by here which means match any non-white space character.

my @list = split /\S+/, $string;

Or better yet, just match your whitespace instead of having to split.

my @list = $string =~ /\s+/g;
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • This looks to be the best answer, especially since he beat me to the second option, which is probably the best. – vol7ron May 18 '14 at 14:46
1

\S splits on any non-whitespace. However, if you want to include tabs and newlines, then you should use (single character space). More than likely what you want is the \S as hwnd has provided.

my $string = q{The    quick  brown fox    jumps over   the lazy dog};
my @values = split /[^ ]+/, $string;
Community
  • 1
  • 1
vol7ron
  • 40,809
  • 21
  • 119
  • 172
0

why not just look for the spaces instead of splitting by non-space characters?
pattern = (\s+) Demo

alpha bravo
  • 7,838
  • 1
  • 19
  • 23