I would like to split a string witch has a variable whitespace characters, but a get a lot of empty lines which I would like to eliminate.this code
$text = "Video Video Audio Audio VBI VBI"$text.Split()outputs this
VideoVideoAudioAudioVBIVBIPS H:\>and I would like this
VideoVideoAudio AudioVBIVBIVery late edit:
Noticed this question is still getting a lot of views, so I would like to clarify that I had no knowledge of Functional Programming or Regular Expressions when I asked this question.
All the solutions mentioned here apply as there are multiple ways to remove whitespace and create an array from a string.
Best Answer
You can use PowerShell's -split operator which uses regular expressions.
"Video Video Audio Audio VBI VBI" -split '\s+'As noted by @StijnDeVos, this does not remove leading/trailing whitespace.
Here, the \s represents whitespace characters, and the + matches one or more of them. All the more reason to go with @user3554001's answer.
Another option is to filter the empty strings.
"Video Video Audio Audio VBI VBI".split()| where {$_}you can use this snippet to eliminate empty lines :
$text.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)-split "Video Video Audio Audio VBI VBI"
Try this, it replaces more than one instance of a space with a single instance before carrying out the split command:
$($text -replace '\s+', ' ').split()The -split operator takes a regex argument, so just match multiple whitespace characters (\s+):
$Text = $text = "Video Video Audio Audio VBI VBI"$text -split '\s+' -match '\S'VideoVideoAudioAudioVBIVBIAny trailing whitespace after the last one may leave you will a null entry, so the -match will eliminate anything that is only whitespace.
other solution :
$text -split ' ' | where {$_.Trim() -ne ''}or :
$text.Split(' ').Where({$_.Trim() -ne ''})