Apologies if this is an obvious one, but I've tried so many things to make this work... In VB (which I'm more familiar with) I believe it would be fine.
I'm trying to split a string with e delimiter of " - ". The spaces are crucial, as there are '-'s elsewhere in the string, but not to be delimited.
"This-string - contains - some-hyphens".Split(' - ')
This should (in my brain) return 3 elements:
This-string contains some-hyphens
Unfortunately, I getting 9+ elements depending on how I play with the Split
method.
This string contains some hyphens
It's clearly splitting on -
alone, but also seems to be splitting on spaces, and ignoring the ' - '
format.
Major Minor Build Revision ----- ----- ----- -------- 5 1 17134 228
The String.Split
method overload you're using accepts char[]
, so powershell is being nice and splitting up your string for you. If you want to use a string, you need to pass StringSplitOptions
:
'This-string - contains - some-hyphens'.Split((,' - '), [StringSplitOptions]::RemoveEmptyEntries)
In testing, I needed to use a unary array operator ,
to force the parser to use the correct overload.
The more powershell-esque way is to use the -split
operator which operates using regex:
'This-string - contains - some-hyphens' -split ' - '
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