如何从特定模式获取子字符串

时间:2019-11-05 09:41:36

标签: powershell

我有一个字符串值数组,例如$dirSourceFolder = "$DeliveryStore\BBG\Port"。从这里我只想提取BBG。

我们可以使用不同的值,例如$directoryServices = "$DeliveryStore\BBG", $ddS ="$DeliveryStore\BBG\Port\Function\CDE",但是$DeliveryStore\总是很常见。

在每种情况下,我都只需要BBG。

我已经使用IndexOf尝试过此操作,但无法获得结果。请协助。

2 个答案:

答案 0 :(得分:1)

这可能有效:

($dirSourceFolder -split "\\")[1]

答案 1 :(得分:0)

您还可以使用Regex:

$substring = if ($dirSourceFolder -match '\\?(BBG)\\?') { $matches[1] }

或(区分大小写)

$substring = [regex]::Match($dirSourceFolder, '\\?(BBG)\\?').Groups[1].Value

或与上述相同,但现在不区分大小写

$caseInsensitive = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase
$substring = [regex]::Match($dirSourceFolder, '\\?(bbg)\\?', $caseInsensitive).Groups[1].Value

全部将输出

  

BBG

P.S。使用IndexOf也可以,但是需要更多的努力:

$index = $dirSourceFolder.IndexOf('\BBG\')  #'# include the backslashes
if ($index -ge 0) { 
    $substring = $dirSourceFolder.Substring($index + 1, 'BBG'.Length)
}