Reputation: 13400
I have string $x
from a TextBox:
I want to split this string to an array of strings without the '*'.
I run: $a = $x.Split("*")
but I received double spaces in the "7-zip":
Suggestion 1:
Here they suggested to user -split
but when using it I received a string (array of chars), not an array of strings:
Suggestion 2:
In this blog and on this question they suggested to use [System.StringSplitOptions]::RemoveEmptyEntrie
+ foreach
(in the blog) in order to parse the un-wanted spaces.
I tried:
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$b = $x.Split("*", $option) |foreach {
$_.Split(" ", $option)
}
How can I split a string to an array of strings separated by "*" ?
Upvotes: 3
Views: 909
Reputation: 174465
As you've found out, you can remove the "blank" entry after the last occurrence of *
with [StringSplitOptions]::RemoveEmptyEntries
.
Now, all you need to do to remove unwanted space around the words, is to call Trim()
:
$x = @"
ccleaner*
7-zip*
"@
$Words = $x.Split('*',[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object {
$_.Trim()
}
PS C:\> $Words[0]
ccleaner
PS C:\> $Words[0]
7-zip
PS C:\>
You can also use -split
(you only need a single \
to escape *
) and then filter out empty entries with Where-Object
:
"a*b* *c" -split "\*" | Where-Object { $_ -notmatch "^\s+$" }| ForEach-Object { $_.Trim() }
or the other way around (use Where-Object
after removing whitespace):
"a*b* *c" -split "\*" | ForEach-Object { $_.Trim() } | Where-Object { $_ }
You could also use -replace
to remove leading and trailing whitespace (basically, the regex version of Trim()
):
" a b " -replace "^\s+|\s+$",""
# results in "a b"
Upvotes: 4