Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 441 Vote(s) - 3.64 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split string with variable whitespace characters in Powershell

#1
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.
Reply

#2
you can use this snippet to eliminate empty lines :

$text.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
Reply

#3
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()
Reply

#4
`-split "Video Video Audio Audio VBI VBI"`
Reply

#5
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.
Reply

#6
other solution :

$text -split ' ' | where {$_.Trim() -ne ''}

or :

$text.Split(' ').Where({$_.Trim() -ne ''})
Reply

#7
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 {$_}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through