2017-06-05 68 views
1

我開始字符串是:如何提取複雜的字符串字符串?

$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

這可能是有益的[使用PowerShell來替換字符串文本(https://blogs.technet.microsoft.com/heyscriptingguy/2011/03/21/use-powershell-to-replace-text-在弦/) – FortyTwo

回答

2

假設串總是有這種形式,你有興趣在第二和第三部分:

# $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 "\" 
+0

THX但我的字符串並不總是這種形式。所以我適應您的代碼,但我需要你的幫助來替換功能。見我的帖子更新 – Ferfa

+0

與元素的通用號碼涉及@Ferfa查看更新。 – gms0ulman

+0

我使用PowerShell 2.0 :(:(:(所以SkipLast不存在 – Ferfa

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] 
} 
1

只是做:

$grp = "DL-test1-test2-RW" 
$arraygrp=$grp.Split("-") 
$arraygrp[1..($arraygrp.Count -2)] -join "\" 

or this

$grp.Substring($grp.IndexOf('-') +1, $grp.LastIndexOf('-')-$grp.IndexOf('-')-1).Replace('-', '\')