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
Video
Video
Audio
Audio
VBI
VBI
PS H:\>
and I would like this
Video
Video
Audio
Audio
VBI
VBI
Very 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.
Use Split() to Split String into Multiple Variables In the above PowerShell script, the $topic stores the string value. We have used the Split() function over $topic to split the string into multiple substrings. If no values are passed to the Split() function takes white space as default.
To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.
When you want to extract a part of a string in PowerShell we can use the Substring() method. This method allows us to specify the start and length of the substring that we want to extract from a string.
Use one of the following patterns to split more than one string: Use the binary split operator (<string[]> -split <delimiter>) Enclose all the strings in parentheses. Store the strings in a variable then submit the variable to the split operator.
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'
Video
Video
Audio
Audio
VBI
VBI
Any trailing whitespace after the last one may leave you will a null entry, so the -match will eliminate anything that is only whitespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With