Reputation: 2041
I'm trying to figure out the regex with powershell, and can't seem to get what I want.
Given the string...
John Doe - Specialist - Data - Person
I want to extract the first and list name from this string and add it to an array. I am trying the following...
$firstName = @()
$lastName = @()
$string = 'John Doe - Specialist - Data - Person'
$firstName += $string -replace '\s+*','' #does not work
$lastName += $string -replace '\*\s+\*','\*' #does not work
So far, this works...
$firstName, $lastName = $string -split "\s"
$lastName, $junk = $lastName -split "\s"
$firstNames += $firstName
$lastNames += $lastName
But it's messy, and I want to know if there is a better way to handle this.
Upvotes: 1
Views: 10728
Reputation: 1
This worked fine for me:
PS C:\scripts> $fullname = "John Mathew Kenneth"
PS C:\scripts> $firstname, $lastname = $fullname -split " " , 2
PS C:\scripts> $firstname
John
PS C:\scripts> $lastname
Mathew Kenneth
Upvotes: 0
Reputation: 1325
Try this:
$string = 'John Doe - Specialist - Data - Person'
$firstName = $string.split(" ")[0]
$lastName = $string.split(" ")[1]
$firstName
$lastName
This will output
John
Doe
It splits on space and selects the first and last name
Edit based on your Code:
$string = 'John Doe - Specialist - Data - Person'
$firstNames += $string.split(" ")[0]
$lastNames += $string.split(" ")[1]
Upvotes: 3