Powershell 如何从字符串中提取名字和姓氏
我试图用powershell计算正则表达式,但似乎无法得到我想要的 给定字符串Powershell 如何从字符串中提取名字和姓氏,powershell,powershell-3.0,Powershell,Powershell 3.0,我试图用powershell计算正则表达式,但似乎无法得到我想要的 给定字符串 John Doe - Specialist - Data - Person 我想从这个字符串中提取第一个和列表名,并将其添加到数组中。我正在尝试以下方法 $firstName = @() $lastName = @() $string = 'John Doe - Specialist - Data - Person' $firstName += $string -replace '\s+*','' #does n
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
它在空间上拆分并选择名字和姓氏
根据您的代码进行编辑:
$string = 'John Doe - Specialist - Data - Person'
$firstNames += $string.split(" ")[0]
$lastNames += $string.split(" ")[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]
这对我来说很好:
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
这对我来说很好:
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
谢谢实际上,我将其更改为此
$string.split(“\s+”)[0]
,以防用户意外输入超过1个空格。问题是,我从csv文件中获取此字符串。因此,当我尝试$\u StringName.split(“”[0]
时,它不起作用。知道为什么吗?我还没有测试过它,但我认为您需要$\u.StringName.split(“”[0]
您的权限。所以,对空白进行硬编码,它会检测1个或多个空白(在文本之间)还是仅检测1个空白(在文本之间)?没关系,我只是添加了空格,它仍然有效。再次感谢:)谢谢!实际上,我将其更改为此$string.split(“\s+”)[0]
,以防用户意外输入超过1个空格。问题是,我从csv文件中获取此字符串。因此,当我尝试$\u StringName.split(“”[0]
时,它不起作用。知道为什么吗?我还没有测试过它,但我认为您需要$\u.StringName.split(“”[0]
您的权限。所以,对空白进行硬编码,它会检测1个或多个空白(在文本之间)还是仅检测1个空白(在文本之间)?没关系,我只是添加了空格,它仍然有效。再次感谢:)