Search code examples
powershellpowershell-3.0

How to extract first and last name from a string


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

Update

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.


Solution

  • 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]