3

I have string $x from a TextBox:
enter image description here

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": enter image description here

Suggestion 1:
Here they suggested to user -split but when using it I received a string (array of chars), not an array of strings:
enter image description here

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)
}

But it didn't help:
enter image description here

How can I split a string to an array of strings separated by "*" ?

0

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Make the regular expression \*`n? and you don't need the extra Trim() call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.