My $string.split() doesn't work

I’m parsing a file with the format:

Website: 'https://mycoolsite.com'

With:

$line_data = $line.split("\s+")
Write-Host "`$line_data[0] is $line_data[0]"

But getting:

$line_data[0] is Website:    https://mycoolsite.com[0]

Obviously I’m doing something wrong, just not sure what. Suggestions?

On a side note, I prefer $string.split() to $string -split, since the former is like other languages I use. :slight_smile:

Addendum: Powershell 7.5.0

While the proper PowerShell operator -split works with regex does the [STRING] method .split() not use regex.

Stay with the genuine/proper PowerShell syntax/operators. Use the -split operator
Here you can read more about operators:

('Website:    https://mycoolsite.com' -split '\s+')[1]

PowerShell is not like other languages. I’d recommend - at least as long as you are a beginner - to stay with the documented PowerShell cmdlets, operators, functions and so on.

3 Likes

I agree with @Olaf that -split is the preferred way; that’s what I would do. However, as an alternative, you could use Regex.Split

Note, your output requires the subexpression operator to output properly:

$line = "Website:    'https://mycoolsite.com'"
$line_data = [regex]::Split($line,'\s+')
Write-Host "`$line_data[0] is $($line_data[0])"

Thanks! Both -split and [regex]::Split work once I use the subexpression operator. I read about that yesterday but didn’t think to try it here.

The on-line tutorials I found used both -split and $string.split(). None had [regex]::Split.

Hrmph…forum won’t let me mark both replies as “solution”. :frowning:

Pick one - it does not matter that much. If someone searches for a solution for the same or a similar issue the post with the marked answer can be found. :man_shrugging: