我的开始字符串是:
$grp = DL-Test1-Test2-RW"
我的目标是
$grp = "Test1\Test2"
所以我需要在第一个和最后一个“ - ”字符之间保留字符串。并替换 - 通过\
已更新 我试过这个:
$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion
答案 0 :(得分:2)
假设字符串始终具有此形式,并且您对第2和第3部分感兴趣:
# $grp.Split("x") - split string on character x, creating an array
# $grp.Split("x")[n] - get the nth element of the array
# x,y -join "\" join the array elements x and y into a string, with "\" inbetween
($grp.Split("-")[1],$grp.Split("-")[2]) -join "\"
编辑 - 适用于通用数量的元素
$($grp.Split("-") | Select-Object -SkipLast 1 | Select-Object -Last ($grp.Split("-").count - 2)) -join "\"
多行:
$Descritpion = $grp.Split("-")
$Descritpion = $Descritpion | Select-Object -SkipLast 1
$Descritpion = $Descritpion | Select-Object -Last ($grp.Split("-").count - 2)
$Descritpion = $Descritpion-join "\"
答案 1 :(得分:1)
就这样做:
$grp = "DL-test1-test2-RW"
$arraygrp=$grp.Split("-")
$arraygrp[1..($arraygrp.Count -2)] -join "\"
或者
$grp.Substring($grp.IndexOf('-') +1, $grp.LastIndexOf('-')-$grp.IndexOf('-')-1 ).Replace('-', '\')
答案 2 :(得分:0)
您也可以使用正则表达式
$grp = "DL-Test1-Test2-RW"
$regex = "-(.*)-(.*)-"
if ($grp -match $regex){
$Matches[1] + "\" + $Matches[2]
}
如果您的字符串在开始和结束之间可以包含更多组,请尝试使用
$grp = "DL-Test1-Test2-Test3-Test4-RW"
$regex = "-(.*-){1,999}(.*)-"
if ($grp -match $regex){
$Matches[1].replace('-','\') + $matches[2]
}