如何从字符串中提取名字和姓氏
How to extract first and last name from a string
我试图用 powershell 找出正则表达式,但似乎无法得到我想要的东西。
给定字符串...
John Doe - Specialist - Data - Person
我想从此字符串中提取第一个和列表名称并将其添加到一个数组中。我正在尝试以下...
$firstName = @()
$lastName = @()
$string = 'John Doe - Specialist - Data - Person'
$firstName += $string -replace '\s+*','' #does not work
$lastName += $string -replace '\*\s+\*','\*' #does not work
更新
到目前为止,这有效...
$firstName, $lastName = $string -split "\s"
$lastName, $junk = $lastName -split "\s"
$firstNames += $firstName
$lastNames += $lastName
但是很乱,想知道有没有更好的办法来处理
试试这个:
$string = 'John Doe - Specialist - Data - Person'
$firstName = $string.split(" ")[0]
$lastName = $string.split(" ")[1]
$firstName
$lastName
这将输出
John
Doe
它在 space 上拆分并选择名字和姓氏
根据您的代码进行编辑:
$string = 'John Doe - Specialist - Data - Person'
$firstNames += $string.split(" ")[0]
$lastNames += $string.split(" ")[1]
这对我来说效果很好:
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
我试图用 powershell 找出正则表达式,但似乎无法得到我想要的东西。
给定字符串...
John Doe - Specialist - Data - Person
我想从此字符串中提取第一个和列表名称并将其添加到一个数组中。我正在尝试以下...
$firstName = @()
$lastName = @()
$string = 'John Doe - Specialist - Data - Person'
$firstName += $string -replace '\s+*','' #does not work
$lastName += $string -replace '\*\s+\*','\*' #does not work
更新
到目前为止,这有效...
$firstName, $lastName = $string -split "\s"
$lastName, $junk = $lastName -split "\s"
$firstNames += $firstName
$lastNames += $lastName
但是很乱,想知道有没有更好的办法来处理
试试这个:
$string = 'John Doe - Specialist - Data - Person'
$firstName = $string.split(" ")[0]
$lastName = $string.split(" ")[1]
$firstName
$lastName
这将输出
John
Doe
它在 space 上拆分并选择名字和姓氏
根据您的代码进行编辑:
$string = 'John Doe - Specialist - Data - Person'
$firstNames += $string.split(" ")[0]
$lastNames += $string.split(" ")[1]
这对我来说效果很好:
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