我正试图用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
但它很混乱,我想知道是否有更好的方法来解决这个问题。
答案 0 :(得分:1)
试试这个:
$string = 'John Doe - Specialist - Data - Person'
$firstName = $string.split(" ")[0]
$lastName = $string.split(" ")[1]
$firstName
$lastName
这将输出
John
Doe
它在空格上分割并选择名字和姓氏
根据您的代码进行修改:
$string = 'John Doe - Specialist - Data - Person'
$firstNames += $string.split(" ")[0]
$lastNames += $string.split(" ")[1]
答案 1 :(得分:0)
这对我来说很好:
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