Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split method splitting by a string which includes spaces

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
like image 696
EndureChaos Avatar asked Jan 27 '23 08:01

EndureChaos


1 Answers

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 ' - '
like image 184
Maximilian Burszley Avatar answered Feb 02 '23 10:02

Maximilian Burszley