Powershell split string on multiple conditions

心不动则不痛 提交于 2019-12-12 02:59:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!