问题
I have a csv file where I am extracting a first and last name from a column, to seperate them in their own columns.
So given the string:
'John Doe - Generic- Random'
I would use the split(" ")
to extract the first and last name
$string = 'John Doe - Generic- Random'
$firstName = $string.split(" ")[0]
$lastName = $string.split(" ")[1]
First Issue
I found an issue where after the last name, sometimes the string does not have a space. For example
$string = 'John Doe-Generic-Random'
How would I get the last name Doe
with out the rest. How can I apply the split for two conditions of " "
and "-"
2nd Issue
Some strings only have a first name. For example...
$string = 'John - Generic - Random
How can I assign the last name as $null if this is the case?
回答1:
Looks like this is working...
$string = 'John Doe - Generic- Random'
$firstName = $string -split {$_ -eq " " -or $_ -eq "-"}
$firstName[0]
$lastName = $string -split {$_ -eq " " -or $_ -eq "-"}
$firstName[1]
If there is no last name, it will be blank in the column Last Name.
If there is a last name but no space between the lastName-Info, it will exclude the -Info and add the lastName to the Last Name Column.
来源:https://stackoverflow.com/questions/34915310/powershell-split-string-on-multiple-conditions